blob: 0a5b2da358243000d25785aa18a7997409e7b331 [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.
Tim Peters38330fe2004-08-30 16:19:24 +0000251
Edward Loperac20f572004-08-12 02:02:24 +0000252OPTIONFLAGS_BY_NAME = {}
253def register_optionflag(name):
254 flag = 1 << len(OPTIONFLAGS_BY_NAME)
255 OPTIONFLAGS_BY_NAME[name] = flag
256 return flag
257
258DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
259DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
260NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
261ELLIPSIS = register_optionflag('ELLIPSIS')
Tim Peters38330fe2004-08-30 16:19:24 +0000262
263COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
264 DONT_ACCEPT_BLANKLINE |
265 NORMALIZE_WHITESPACE |
266 ELLIPSIS)
267
Edward Loper71f55af2004-08-26 01:41:51 +0000268REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
269REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
270REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
Edward Lopera89f88d2004-08-26 02:45:51 +0000271REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
Edward Loperac20f572004-08-12 02:02:24 +0000272
Tim Peters38330fe2004-08-30 16:19:24 +0000273REPORTING_FLAGS = (REPORT_UDIFF |
274 REPORT_CDIFF |
275 REPORT_NDIFF |
276 REPORT_ONLY_FIRST_FAILURE)
277
Edward Loperac20f572004-08-12 02:02:24 +0000278# Special string markers for use in `want` strings:
279BLANKLINE_MARKER = '<BLANKLINE>'
280ELLIPSIS_MARKER = '...'
281
Tim Peters8485b562004-08-04 18:46:34 +0000282######################################################################
283## Table of Contents
284######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000285# 1. Utility Functions
286# 2. Example & DocTest -- store test cases
287# 3. DocTest Parser -- extracts examples from strings
288# 4. DocTest Finder -- extracts test cases from objects
289# 5. DocTest Runner -- runs test cases
290# 6. Test Functions -- convenient wrappers for testing
291# 7. Tester Class -- for backwards compatibility
292# 8. Unittest Support
293# 9. Debugging Support
294# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000295
Tim Peters8485b562004-08-04 18:46:34 +0000296######################################################################
297## 1. Utility Functions
298######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000299
300def is_private(prefix, base):
301 """prefix, base -> true iff name prefix + "." + base is "private".
302
303 Prefix may be an empty string, and base does not contain a period.
304 Prefix is ignored (although functions you write conforming to this
305 protocol may make use of it).
306 Return true iff base begins with an (at least one) underscore, but
307 does not both begin and end with (at least) two underscores.
308
309 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000310 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000311 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000312 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000313 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000314 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000315 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000316 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000317 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000318 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000319 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000320 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000321 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000322 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000323 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000324 warnings.warn("is_private is deprecated; it wasn't useful; "
325 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000326 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000327 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
328
Tim Peters8485b562004-08-04 18:46:34 +0000329def _extract_future_flags(globs):
330 """
331 Return the compiler-flags associated with the future features that
332 have been imported into the given namespace (globs).
333 """
334 flags = 0
335 for fname in __future__.all_feature_names:
336 feature = globs.get(fname, None)
337 if feature is getattr(__future__, fname):
338 flags |= feature.compiler_flag
339 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000340
Tim Peters8485b562004-08-04 18:46:34 +0000341def _normalize_module(module, depth=2):
342 """
343 Return the module specified by `module`. In particular:
344 - If `module` is a module, then return module.
345 - If `module` is a string, then import and return the
346 module with that name.
347 - If `module` is None, then return the calling module.
348 The calling module is assumed to be the module of
349 the stack frame at the given depth in the call stack.
350 """
351 if inspect.ismodule(module):
352 return module
353 elif isinstance(module, (str, unicode)):
354 return __import__(module, globals(), locals(), ["*"])
355 elif module is None:
356 return sys.modules[sys._getframe(depth).f_globals['__name__']]
357 else:
358 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000359
Edward Loperaacf0832004-08-26 01:19:50 +0000360def _indent(s, indent=4):
Tim Peters8485b562004-08-04 18:46:34 +0000361 """
Edward Loperaacf0832004-08-26 01:19:50 +0000362 Add the given number of space characters to the beginning every
363 non-blank line in `s`, and return the result.
Tim Peters8485b562004-08-04 18:46:34 +0000364 """
Edward Loperaacf0832004-08-26 01:19:50 +0000365 # This regexp matches the start of non-blank lines:
366 return re.sub('(?m)^(?!$)', indent*' ', s)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000367
Edward Loper8e4a34b2004-08-12 02:34:27 +0000368def _exception_traceback(exc_info):
369 """
370 Return a string containing a traceback message for the given
371 exc_info tuple (as returned by sys.exc_info()).
372 """
373 # Get a traceback message.
374 excout = StringIO()
375 exc_type, exc_val, exc_tb = exc_info
376 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
377 return excout.getvalue()
378
Tim Peters8485b562004-08-04 18:46:34 +0000379# Override some StringIO methods.
380class _SpoofOut(StringIO):
381 def getvalue(self):
382 result = StringIO.getvalue(self)
383 # If anything at all was written, make sure there's a trailing
384 # newline. There's no way for the expected output to indicate
385 # that a trailing newline is missing.
386 if result and not result.endswith("\n"):
387 result += "\n"
388 # Prevent softspace from screwing up the next test case, in
389 # case they used print with a trailing comma in an example.
390 if hasattr(self, "softspace"):
391 del self.softspace
392 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000393
Tim Peters8485b562004-08-04 18:46:34 +0000394 def truncate(self, size=None):
395 StringIO.truncate(self, size)
396 if hasattr(self, "softspace"):
397 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000398
Tim Peters26b3ebb2004-08-19 08:10:08 +0000399# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000400def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000401 """
402 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000403 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000404 False
405 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000406 if ELLIPSIS_MARKER not in want:
407 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000408
Tim Peters26b3ebb2004-08-19 08:10:08 +0000409 # Find "the real" strings.
410 ws = want.split(ELLIPSIS_MARKER)
411 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000412
Tim Petersdc5de3b2004-08-19 14:06:20 +0000413 # Deal with exact matches possibly needed at one or both ends.
414 startpos, endpos = 0, len(got)
415 w = ws[0]
416 if w: # starts with exact match
417 if got.startswith(w):
418 startpos = len(w)
419 del ws[0]
420 else:
421 return False
422 w = ws[-1]
423 if w: # ends with exact match
424 if got.endswith(w):
425 endpos -= len(w)
426 del ws[-1]
427 else:
428 return False
429
430 if startpos > endpos:
431 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000432 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000433 return False
434
435 # For the rest, we only need to find the leftmost non-overlapping
436 # match for each piece. If there's no overall match that way alone,
437 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000438 for w in ws:
439 # w may be '' at times, if there are consecutive ellipses, or
440 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000441 # Search for an empty string succeeds, and doesn't change startpos.
442 startpos = got.find(w, startpos, endpos)
443 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000444 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000445 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000446
Tim Petersdc5de3b2004-08-19 14:06:20 +0000447 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000448
Edward Loper00f8da72004-08-26 18:05:07 +0000449def _comment_line(line):
450 "Return a commented form of the given line"
451 line = line.rstrip()
452 if line:
453 return '# '+line
454 else:
455 return '#'
456
Edward Loper2de91ba2004-08-27 02:07:46 +0000457class _OutputRedirectingPdb(pdb.Pdb):
458 """
459 A specialized version of the python debugger that redirects stdout
460 to a given stream when interacting with the user. Stdout is *not*
461 redirected when traced code is executed.
462 """
463 def __init__(self, out):
464 self.__out = out
465 pdb.Pdb.__init__(self)
466
467 def trace_dispatch(self, *args):
468 # Redirect stdout to the given stream.
469 save_stdout = sys.stdout
470 sys.stdout = self.__out
471 # Call Pdb's trace dispatch method.
472 pdb.Pdb.trace_dispatch(self, *args)
473 # Restore stdout.
474 sys.stdout = save_stdout
475
Tim Peters8485b562004-08-04 18:46:34 +0000476######################################################################
477## 2. Example & DocTest
478######################################################################
479## - An "example" is a <source, want> pair, where "source" is a
480## fragment of source code, and "want" is the expected output for
481## "source." The Example class also includes information about
482## where the example was extracted from.
483##
Edward Lopera1ef6112004-08-09 16:14:41 +0000484## - A "doctest" is a collection of examples, typically extracted from
485## a string (such as an object's docstring). The DocTest class also
486## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000487
Tim Peters8485b562004-08-04 18:46:34 +0000488class Example:
489 """
490 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000491 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000492
Edward Loper74bca7a2004-08-12 02:27:44 +0000493 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000494 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000495
Edward Loper74bca7a2004-08-12 02:27:44 +0000496 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000497 from stdout, or a traceback in case of exception). `want` ends
498 with a newline unless it's empty, in which case it's an empty
499 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000500
Edward Lopera6b68322004-08-26 00:05:43 +0000501 - exc_msg: The exception message generated by the example, if
502 the example is expected to generate an exception; or `None` if
503 it is not expected to generate an exception. This exception
504 message is compared against the return value of
505 `traceback.format_exception_only()`. `exc_msg` ends with a
506 newline unless it's `None`. The constructor adds a newline
507 if needed.
508
Edward Loper74bca7a2004-08-12 02:27:44 +0000509 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000510 this Example where the Example begins. This line number is
511 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000512
513 - indent: The example's indentation in the DocTest string.
514 I.e., the number of space characters that preceed the
515 example's first prompt.
516
517 - options: A dictionary mapping from option flags to True or
518 False, which is used to override default options for this
519 example. Any option flags not contained in this dictionary
520 are left at their default value (as specified by the
521 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000522 """
Edward Lopera6b68322004-08-26 00:05:43 +0000523 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
524 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000525 # Normalize inputs.
526 if not source.endswith('\n'):
527 source += '\n'
528 if want and not want.endswith('\n'):
529 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000530 if exc_msg is not None and not exc_msg.endswith('\n'):
531 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000532 # Store properties.
533 self.source = source
534 self.want = want
535 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000536 self.indent = indent
537 if options is None: options = {}
538 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000539 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000540
Tim Peters8485b562004-08-04 18:46:34 +0000541class DocTest:
542 """
543 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000544 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000545
Tim Peters8485b562004-08-04 18:46:34 +0000546 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000547
Tim Peters8485b562004-08-04 18:46:34 +0000548 - globs: The namespace (aka globals) that the examples should
549 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000550
Tim Peters8485b562004-08-04 18:46:34 +0000551 - name: A name identifying the DocTest (typically, the name of
552 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000553
Tim Peters8485b562004-08-04 18:46:34 +0000554 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000555 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000556
Tim Peters8485b562004-08-04 18:46:34 +0000557 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000558 begins, or `None` if the line number is unavailable. This
559 line number is zero-based, with respect to the beginning of
560 the file.
561
562 - docstring: The string that the examples were extracted from,
563 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000564 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000565 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000566 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000567 Create a new DocTest containing the given examples. The
568 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000569 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000570 assert not isinstance(examples, basestring), \
571 "DocTest no longer accepts str; use DocTestParser instead"
572 self.examples = examples
573 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000574 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000575 self.name = name
576 self.filename = filename
577 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000578
579 def __repr__(self):
580 if len(self.examples) == 0:
581 examples = 'no examples'
582 elif len(self.examples) == 1:
583 examples = '1 example'
584 else:
585 examples = '%d examples' % len(self.examples)
586 return ('<DocTest %s from %s:%s (%s)>' %
587 (self.name, self.filename, self.lineno, examples))
588
589
590 # This lets us sort tests by name:
591 def __cmp__(self, other):
592 if not isinstance(other, DocTest):
593 return -1
594 return cmp((self.name, self.filename, self.lineno, id(self)),
595 (other.name, other.filename, other.lineno, id(other)))
596
597######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000598## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000599######################################################################
600
Edward Lopera1ef6112004-08-09 16:14:41 +0000601class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000602 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000603 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000604 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000605 # This regular expression is used to find doctest examples in a
606 # string. It defines three groups: `source` is the source code
607 # (including leading indentation and prompts); `indent` is the
608 # indentation of the first (PS1) line of the source code; and
609 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000610 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000611 # Source consists of a PS1 line followed by zero or more PS2 lines.
612 (?P<source>
613 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
614 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
615 \n?
616 # Want consists of any non-blank lines that do not start with PS1.
617 (?P<want> (?:(?![ ]*$) # Not a blank line
618 (?![ ]*>>>) # Not a line starting with PS1
619 .*$\n? # But any other line
620 )*)
621 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000622
Edward Lopera6b68322004-08-26 00:05:43 +0000623 # A regular expression for handling `want` strings that contain
624 # expected exceptions. It divides `want` into three pieces:
625 # - the traceback header line (`hdr`)
626 # - the traceback stack (`stack`)
627 # - the exception message (`msg`), as generated by
628 # traceback.format_exception_only()
629 # `msg` may have multiple lines. We assume/require that the
630 # exception message is the first non-indented line starting with a word
631 # character following the traceback header line.
632 _EXCEPTION_RE = re.compile(r"""
633 # Grab the traceback header. Different versions of Python have
634 # said different things on the first traceback line.
635 ^(?P<hdr> Traceback\ \(
636 (?: most\ recent\ call\ last
637 | innermost\ last
638 ) \) :
639 )
640 \s* $ # toss trailing whitespace on the header.
641 (?P<stack> .*?) # don't blink: absorb stuff until...
642 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
643 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
644
Tim Peters7ea48dd2004-08-13 01:52:59 +0000645 # A callable returning a true value iff its argument is a blank line
646 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000647 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000648
Edward Loper00f8da72004-08-26 18:05:07 +0000649 def parse(self, string, name='<string>'):
650 """
651 Divide the given string into examples and intervening text,
652 and return them as a list of alternating Examples and strings.
653 Line numbers for the Examples are 0-based. The optional
654 argument `name` is a name identifying this string, and is only
655 used for error messages.
656 """
657 string = string.expandtabs()
658 # If all lines begin with the same indentation, then strip it.
659 min_indent = self._min_indent(string)
660 if min_indent > 0:
661 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
662
663 output = []
664 charno, lineno = 0, 0
665 # Find all doctest examples in the string:
Edward Loper2de91ba2004-08-27 02:07:46 +0000666 for m in self._EXAMPLE_RE.finditer(string):
Edward Loper00f8da72004-08-26 18:05:07 +0000667 # Add the pre-example text to `output`.
668 output.append(string[charno:m.start()])
669 # Update lineno (lines before this example)
670 lineno += string.count('\n', charno, m.start())
671 # Extract info from the regexp match.
672 (source, options, want, exc_msg) = \
673 self._parse_example(m, name, lineno)
674 # Create an Example, and add it to the list.
675 if not self._IS_BLANK_OR_COMMENT(source):
676 output.append( Example(source, want, exc_msg,
677 lineno=lineno,
678 indent=min_indent+len(m.group('indent')),
679 options=options) )
680 # Update lineno (lines inside this example)
681 lineno += string.count('\n', m.start(), m.end())
682 # Update charno.
683 charno = m.end()
684 # Add any remaining post-example text to `output`.
685 output.append(string[charno:])
686 return output
687
Edward Lopera1ef6112004-08-09 16:14:41 +0000688 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000689 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000690 Extract all doctest examples from the given string, and
691 collect them into a `DocTest` object.
692
693 `globs`, `name`, `filename`, and `lineno` are attributes for
694 the new `DocTest` object. See the documentation for `DocTest`
695 for more information.
696 """
697 return DocTest(self.get_examples(string, name), globs,
698 name, filename, lineno, string)
699
700 def get_examples(self, string, name='<string>'):
701 """
702 Extract all doctest examples from the given string, and return
703 them as a list of `Example` objects. Line numbers are
704 0-based, because it's most common in doctests that nothing
705 interesting appears on the same line as opening triple-quote,
706 and so the first interesting line is called \"line 1\" then.
707
708 The optional argument `name` is a name identifying this
709 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000710 """
Edward Loper00f8da72004-08-26 18:05:07 +0000711 return [x for x in self.parse(string, name)
712 if isinstance(x, Example)]
Edward Loper7c748462004-08-09 02:06:06 +0000713
Edward Loper74bca7a2004-08-12 02:27:44 +0000714 def _parse_example(self, m, name, lineno):
715 """
716 Given a regular expression match from `_EXAMPLE_RE` (`m`),
717 return a pair `(source, want)`, where `source` is the matched
718 example's source code (with prompts and indentation stripped);
719 and `want` is the example's expected output (with indentation
720 stripped).
721
722 `name` is the string's name, and `lineno` is the line number
723 where the example starts; both are used for error messages.
724 """
Edward Loper7c748462004-08-09 02:06:06 +0000725 # Get the example's indentation level.
726 indent = len(m.group('indent'))
727
728 # Divide source into lines; check that they're properly
729 # indented; and then strip their indentation & prompts.
730 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000731 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000732 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000733 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000734
Tim Petersc5049152004-08-22 17:34:58 +0000735 # Divide want into lines; check that it's properly indented; and
736 # then strip the indentation. Spaces before the last newline should
737 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000738 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000739 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000740 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
741 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000742 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000743 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000744 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000745
Edward Lopera6b68322004-08-26 00:05:43 +0000746 # If `want` contains a traceback message, then extract it.
747 m = self._EXCEPTION_RE.match(want)
748 if m:
749 exc_msg = m.group('msg')
750 else:
751 exc_msg = None
752
Edward Loper00f8da72004-08-26 18:05:07 +0000753 # Extract options from the source.
754 options = self._find_options(source, name, lineno)
755
756 return source, options, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000757
Edward Loper74bca7a2004-08-12 02:27:44 +0000758 # This regular expression looks for option directives in the
759 # source code of an example. Option directives are comments
760 # starting with "doctest:". Warning: this may give false
761 # positives for string-literals that contain the string
762 # "#doctest:". Eliminating these false positives would require
763 # actually parsing the string; but we limit them by ignoring any
764 # line containing "#doctest:" that is *followed* by a quote mark.
765 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
766 re.MULTILINE)
767
768 def _find_options(self, source, name, lineno):
769 """
770 Return a dictionary containing option overrides extracted from
771 option directives in the given source string.
772
773 `name` is the string's name, and `lineno` is the line number
774 where the example starts; both are used for error messages.
775 """
776 options = {}
777 # (note: with the current regexp, this will match at most once:)
778 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
779 option_strings = m.group(1).replace(',', ' ').split()
780 for option in option_strings:
781 if (option[0] not in '+-' or
782 option[1:] not in OPTIONFLAGS_BY_NAME):
783 raise ValueError('line %r of the doctest for %s '
784 'has an invalid option: %r' %
785 (lineno+1, name, option))
786 flag = OPTIONFLAGS_BY_NAME[option[1:]]
787 options[flag] = (option[0] == '+')
788 if options and self._IS_BLANK_OR_COMMENT(source):
789 raise ValueError('line %r of the doctest for %s has an option '
790 'directive on a line with no example: %r' %
791 (lineno, name, source))
792 return options
793
Edward Lopera5db6002004-08-12 02:41:30 +0000794 # This regular expression finds the indentation of every non-blank
795 # line in a string.
Edward Loper00f8da72004-08-26 18:05:07 +0000796 _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
Edward Lopera5db6002004-08-12 02:41:30 +0000797
798 def _min_indent(self, s):
799 "Return the minimum indentation of any non-blank line in `s`"
Edward Loper00f8da72004-08-26 18:05:07 +0000800 indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
801 if len(indents) > 0:
802 return min(indents)
Tim Petersdd0e4752004-08-09 03:31:56 +0000803 else:
Edward Loper00f8da72004-08-26 18:05:07 +0000804 return 0
Edward Loper7c748462004-08-09 02:06:06 +0000805
Edward Lopera1ef6112004-08-09 16:14:41 +0000806 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000807 """
808 Given the lines of a source string (including prompts and
809 leading indentation), check to make sure that every prompt is
810 followed by a space character. If any line is not followed by
811 a space character, then raise ValueError.
812 """
Edward Loper7c748462004-08-09 02:06:06 +0000813 for i, line in enumerate(lines):
814 if len(line) >= indent+4 and line[indent+3] != ' ':
815 raise ValueError('line %r of the docstring for %s '
816 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000817 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000818 line[indent:indent+3], line))
819
Edward Lopera1ef6112004-08-09 16:14:41 +0000820 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000821 """
822 Check that every line in the given list starts with the given
823 prefix; if any line does not, then raise a ValueError.
824 """
Edward Loper7c748462004-08-09 02:06:06 +0000825 for i, line in enumerate(lines):
826 if line and not line.startswith(prefix):
827 raise ValueError('line %r of the docstring for %s has '
828 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000829 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000830
831
832######################################################################
833## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000834######################################################################
835
836class DocTestFinder:
837 """
838 A class used to extract the DocTests that are relevant to a given
839 object, from its docstring and the docstrings of its contained
840 objects. Doctests can currently be extracted from the following
841 object types: modules, functions, classes, methods, staticmethods,
842 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000843 """
844
Edward Lopera1ef6112004-08-09 16:14:41 +0000845 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000846 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000847 """
848 Create a new doctest finder.
849
Edward Lopera1ef6112004-08-09 16:14:41 +0000850 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000851 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000852 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000853 signature for this factory function should match the signature
854 of the DocTest constructor.
855
Tim Peters8485b562004-08-04 18:46:34 +0000856 If the optional argument `recurse` is false, then `find` will
857 only examine the given object, and not any contained objects.
858 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000859 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000860 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000861 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000862 # _namefilter is undocumented, and exists only for temporary backward-
863 # compatibility support of testmod's deprecated isprivate mess.
864 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000865
866 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000867 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000868 """
869 Return a list of the DocTests that are defined by the given
870 object's docstring, or by any of its contained objects'
871 docstrings.
872
873 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000874 the given object. If the module is not specified or is None, then
875 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000876 correct module. The object's module is used:
877
878 - As a default namespace, if `globs` is not specified.
879 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000880 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000881 - To find the name of the file containing the object.
882 - To help find the line number of the object within its
883 file.
884
Tim Petersf3f57472004-08-08 06:11:48 +0000885 Contained objects whose module does not match `module` are ignored.
886
887 If `module` is False, no attempt to find the module will be made.
888 This is obscure, of use mostly in tests: if `module` is False, or
889 is None but cannot be found automatically, then all objects are
890 considered to belong to the (non-existent) module, so all contained
891 objects will (recursively) be searched for doctests.
892
Tim Peters8485b562004-08-04 18:46:34 +0000893 The globals for each DocTest is formed by combining `globs`
894 and `extraglobs` (bindings in `extraglobs` override bindings
895 in `globs`). A new copy of the globals dictionary is created
896 for each DocTest. If `globs` is not specified, then it
897 defaults to the module's `__dict__`, if specified, or {}
898 otherwise. If `extraglobs` is not specified, then it defaults
899 to {}.
900
Tim Peters8485b562004-08-04 18:46:34 +0000901 """
902 # If name was not specified, then extract it from the object.
903 if name is None:
904 name = getattr(obj, '__name__', None)
905 if name is None:
906 raise ValueError("DocTestFinder.find: name must be given "
907 "when obj.__name__ doesn't exist: %r" %
908 (type(obj),))
909
910 # Find the module that contains the given object (if obj is
911 # a module, then module=obj.). Note: this may fail, in which
912 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000913 if module is False:
914 module = None
915 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000916 module = inspect.getmodule(obj)
917
918 # Read the module's source code. This is used by
919 # DocTestFinder._find_lineno to find the line number for a
920 # given object's docstring.
921 try:
922 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
923 source_lines = linecache.getlines(file)
924 if not source_lines:
925 source_lines = None
926 except TypeError:
927 source_lines = None
928
929 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000930 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000931 if module is None:
932 globs = {}
933 else:
934 globs = module.__dict__.copy()
935 else:
936 globs = globs.copy()
937 if extraglobs is not None:
938 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000939
Tim Peters8485b562004-08-04 18:46:34 +0000940 # Recursively expore `obj`, extracting DocTests.
941 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000942 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000943 return tests
944
945 def _filter(self, obj, prefix, base):
946 """
947 Return true if the given object should not be examined.
948 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000949 return (self._namefilter is not None and
950 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000951
952 def _from_module(self, module, object):
953 """
954 Return true if the given object is defined in the given
955 module.
956 """
957 if module is None:
958 return True
959 elif inspect.isfunction(object):
960 return module.__dict__ is object.func_globals
961 elif inspect.isclass(object):
962 return module.__name__ == object.__module__
963 elif inspect.getmodule(object) is not None:
964 return module is inspect.getmodule(object)
965 elif hasattr(object, '__module__'):
966 return module.__name__ == object.__module__
967 elif isinstance(object, property):
968 return True # [XX] no way not be sure.
969 else:
970 raise ValueError("object must be a class or function")
971
Tim Petersf3f57472004-08-08 06:11:48 +0000972 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000973 """
974 Find tests for the given object and any contained objects, and
975 add them to `tests`.
976 """
977 if self._verbose:
978 print 'Finding tests in %s' % name
979
980 # If we've already processed this object, then ignore it.
981 if id(obj) in seen:
982 return
983 seen[id(obj)] = 1
984
985 # Find a test for this object, and add it to the list of tests.
986 test = self._get_test(obj, name, module, globs, source_lines)
987 if test is not None:
988 tests.append(test)
989
990 # Look for tests in a module's contained objects.
991 if inspect.ismodule(obj) and self._recurse:
992 for valname, val in obj.__dict__.items():
993 # Check if this contained object should be ignored.
994 if self._filter(val, name, valname):
995 continue
996 valname = '%s.%s' % (name, valname)
997 # Recurse to functions & classes.
998 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000999 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001000 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001001 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001002
1003 # Look for tests in a module's __test__ dictionary.
1004 if inspect.ismodule(obj) and self._recurse:
1005 for valname, val in getattr(obj, '__test__', {}).items():
1006 if not isinstance(valname, basestring):
1007 raise ValueError("DocTestFinder.find: __test__ keys "
1008 "must be strings: %r" %
1009 (type(valname),))
1010 if not (inspect.isfunction(val) or inspect.isclass(val) or
1011 inspect.ismethod(val) or inspect.ismodule(val) or
1012 isinstance(val, basestring)):
1013 raise ValueError("DocTestFinder.find: __test__ values "
1014 "must be strings, functions, methods, "
1015 "classes, or modules: %r" %
1016 (type(val),))
1017 valname = '%s.%s' % (name, valname)
1018 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001019 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001020
1021 # Look for tests in a class's contained objects.
1022 if inspect.isclass(obj) and self._recurse:
1023 for valname, val in obj.__dict__.items():
1024 # Check if this contained object should be ignored.
1025 if self._filter(val, name, valname):
1026 continue
1027 # Special handling for staticmethod/classmethod.
1028 if isinstance(val, staticmethod):
1029 val = getattr(obj, valname)
1030 if isinstance(val, classmethod):
1031 val = getattr(obj, valname).im_func
1032
1033 # Recurse to methods, properties, and nested classes.
1034 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001035 isinstance(val, property)) and
1036 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001037 valname = '%s.%s' % (name, valname)
1038 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001039 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001040
1041 def _get_test(self, obj, name, module, globs, source_lines):
1042 """
1043 Return a DocTest for the given object, if it defines a docstring;
1044 otherwise, return None.
1045 """
1046 # Extract the object's docstring. If it doesn't have one,
1047 # then return None (no test for this object).
1048 if isinstance(obj, basestring):
1049 docstring = obj
1050 else:
1051 try:
1052 if obj.__doc__ is None:
1053 return None
1054 docstring = str(obj.__doc__)
1055 except (TypeError, AttributeError):
1056 return None
1057
1058 # Don't bother if the docstring is empty.
1059 if not docstring:
1060 return None
1061
1062 # Find the docstring's location in the file.
1063 lineno = self._find_lineno(obj, source_lines)
1064
1065 # Return a DocTest for this object.
1066 if module is None:
1067 filename = None
1068 else:
1069 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001070 if filename[-4:] in (".pyc", ".pyo"):
1071 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001072 return self._parser.get_doctest(docstring, globs, name,
1073 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001074
1075 def _find_lineno(self, obj, source_lines):
1076 """
1077 Return a line number of the given object's docstring. Note:
1078 this method assumes that the object has a docstring.
1079 """
1080 lineno = None
1081
1082 # Find the line number for modules.
1083 if inspect.ismodule(obj):
1084 lineno = 0
1085
1086 # Find the line number for classes.
1087 # Note: this could be fooled if a class is defined multiple
1088 # times in a single file.
1089 if inspect.isclass(obj):
1090 if source_lines is None:
1091 return None
1092 pat = re.compile(r'^\s*class\s*%s\b' %
1093 getattr(obj, '__name__', '-'))
1094 for i, line in enumerate(source_lines):
1095 if pat.match(line):
1096 lineno = i
1097 break
1098
1099 # Find the line number for functions & methods.
1100 if inspect.ismethod(obj): obj = obj.im_func
1101 if inspect.isfunction(obj): obj = obj.func_code
1102 if inspect.istraceback(obj): obj = obj.tb_frame
1103 if inspect.isframe(obj): obj = obj.f_code
1104 if inspect.iscode(obj):
1105 lineno = getattr(obj, 'co_firstlineno', None)-1
1106
1107 # Find the line number where the docstring starts. Assume
1108 # that it's the first line that begins with a quote mark.
1109 # Note: this could be fooled by a multiline function
1110 # signature, where a continuation line begins with a quote
1111 # mark.
1112 if lineno is not None:
1113 if source_lines is None:
1114 return lineno+1
1115 pat = re.compile('(^|.*:)\s*\w*("|\')')
1116 for lineno in range(lineno, len(source_lines)):
1117 if pat.match(source_lines[lineno]):
1118 return lineno
1119
1120 # We couldn't find the line number.
1121 return None
1122
1123######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001124## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001125######################################################################
1126
Tim Peters8485b562004-08-04 18:46:34 +00001127class DocTestRunner:
1128 """
1129 A class used to run DocTest test cases, and accumulate statistics.
1130 The `run` method is used to process a single DocTest case. It
1131 returns a tuple `(f, t)`, where `t` is the number of test cases
1132 tried, and `f` is the number of test cases that failed.
1133
1134 >>> tests = DocTestFinder().find(_TestClass)
1135 >>> runner = DocTestRunner(verbose=False)
1136 >>> for test in tests:
1137 ... print runner.run(test)
1138 (0, 2)
1139 (0, 1)
1140 (0, 2)
1141 (0, 2)
1142
1143 The `summarize` method prints a summary of all the test cases that
1144 have been run by the runner, and returns an aggregated `(f, t)`
1145 tuple:
1146
1147 >>> runner.summarize(verbose=1)
1148 4 items passed all tests:
1149 2 tests in _TestClass
1150 2 tests in _TestClass.__init__
1151 2 tests in _TestClass.get
1152 1 tests in _TestClass.square
1153 7 tests in 4 items.
1154 7 passed and 0 failed.
1155 Test passed.
1156 (0, 7)
1157
1158 The aggregated number of tried examples and failed examples is
1159 also available via the `tries` and `failures` attributes:
1160
1161 >>> runner.tries
1162 7
1163 >>> runner.failures
1164 0
1165
1166 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001167 by an `OutputChecker`. This comparison may be customized with a
1168 number of option flags; see the documentation for `testmod` for
1169 more information. If the option flags are insufficient, then the
1170 comparison may also be customized by passing a subclass of
1171 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001172
1173 The test runner's display output can be controlled in two ways.
1174 First, an output function (`out) can be passed to
1175 `TestRunner.run`; this function will be called with strings that
1176 should be displayed. It defaults to `sys.stdout.write`. If
1177 capturing the output is not sufficient, then the display output
1178 can be also customized by subclassing DocTestRunner, and
1179 overriding the methods `report_start`, `report_success`,
1180 `report_unexpected_exception`, and `report_failure`.
1181 """
1182 # This divider string is used to separate failure messages, and to
1183 # separate sections of the summary.
1184 DIVIDER = "*" * 70
1185
Edward Loper34fcb142004-08-09 02:45:41 +00001186 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001187 """
1188 Create a new test runner.
1189
Edward Loper34fcb142004-08-09 02:45:41 +00001190 Optional keyword arg `checker` is the `OutputChecker` that
1191 should be used to compare the expected outputs and actual
1192 outputs of doctest examples.
1193
Tim Peters8485b562004-08-04 18:46:34 +00001194 Optional keyword arg 'verbose' prints lots of stuff if true,
1195 only failures if false; by default, it's true iff '-v' is in
1196 sys.argv.
1197
1198 Optional argument `optionflags` can be used to control how the
1199 test runner compares expected output to actual output, and how
1200 it displays failures. See the documentation for `testmod` for
1201 more information.
1202 """
Edward Loper34fcb142004-08-09 02:45:41 +00001203 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001204 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001205 verbose = '-v' in sys.argv
1206 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001207 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001208 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001209
Tim Peters8485b562004-08-04 18:46:34 +00001210 # Keep track of the examples we've run.
1211 self.tries = 0
1212 self.failures = 0
1213 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001214
Tim Peters8485b562004-08-04 18:46:34 +00001215 # Create a fake output target for capturing doctest output.
1216 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001217
Tim Peters8485b562004-08-04 18:46:34 +00001218 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001219 # Reporting methods
1220 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001221
Tim Peters8485b562004-08-04 18:46:34 +00001222 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001223 """
Tim Peters8485b562004-08-04 18:46:34 +00001224 Report that the test runner is about to process the given
1225 example. (Only displays a message if verbose=True)
1226 """
1227 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001228 if example.want:
1229 out('Trying:\n' + _indent(example.source) +
1230 'Expecting:\n' + _indent(example.want))
1231 else:
1232 out('Trying:\n' + _indent(example.source) +
1233 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001234
Tim Peters8485b562004-08-04 18:46:34 +00001235 def report_success(self, out, test, example, got):
1236 """
1237 Report that the given example ran successfully. (Only
1238 displays a message if verbose=True)
1239 """
1240 if self._verbose:
1241 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001242
Tim Peters8485b562004-08-04 18:46:34 +00001243 def report_failure(self, out, test, example, got):
1244 """
1245 Report that the given example failed.
1246 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001247 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001248 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001249
Tim Peters8485b562004-08-04 18:46:34 +00001250 def report_unexpected_exception(self, out, test, example, exc_info):
1251 """
1252 Report that the given example raised an unexpected exception.
1253 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001254 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001255 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001256
Edward Loper8e4a34b2004-08-12 02:34:27 +00001257 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001258 out = [self.DIVIDER]
1259 if test.filename:
1260 if test.lineno is not None and example.lineno is not None:
1261 lineno = test.lineno + example.lineno + 1
1262 else:
1263 lineno = '?'
1264 out.append('File "%s", line %s, in %s' %
1265 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001266 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001267 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1268 out.append('Failed example:')
1269 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001270 out.append(_indent(source))
1271 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001272
Tim Peters8485b562004-08-04 18:46:34 +00001273 #/////////////////////////////////////////////////////////////////
1274 # DocTest Running
1275 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001276
Tim Peters8485b562004-08-04 18:46:34 +00001277 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001278 """
Tim Peters8485b562004-08-04 18:46:34 +00001279 Run the examples in `test`. Write the outcome of each example
1280 with one of the `DocTestRunner.report_*` methods, using the
1281 writer function `out`. `compileflags` is the set of compiler
1282 flags that should be used to execute examples. Return a tuple
1283 `(f, t)`, where `t` is the number of examples tried, and `f`
1284 is the number of examples that failed. The examples are run
1285 in the namespace `test.globs`.
1286 """
1287 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001288 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001289
1290 # Save the option flags (since option directives can be used
1291 # to modify them).
1292 original_optionflags = self.optionflags
1293
1294 # Process each example.
Edward Loper2de91ba2004-08-27 02:07:46 +00001295 for examplenum, example in enumerate(test.examples):
1296
Edward Lopera89f88d2004-08-26 02:45:51 +00001297 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1298 # reporting after the first failure.
1299 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1300 failures > 0)
1301
Edward Loper74bca7a2004-08-12 02:27:44 +00001302 # Merge in the example's options.
1303 self.optionflags = original_optionflags
1304 if example.options:
1305 for (optionflag, val) in example.options.items():
1306 if val:
1307 self.optionflags |= optionflag
1308 else:
1309 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001310
1311 # Record that we started this example.
1312 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001313 if not quiet:
1314 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001315
Edward Loper2de91ba2004-08-27 02:07:46 +00001316 # Use a special filename for compile(), so we can retrieve
1317 # the source code during interactive debugging (see
1318 # __patched_linecache_getlines).
1319 filename = '<doctest %s[%d]>' % (test.name, examplenum)
1320
Tim Peters8485b562004-08-04 18:46:34 +00001321 # Run the example in the given context (globs), and record
1322 # any exception that gets raised. (But don't intercept
1323 # keyboard interrupts.)
1324 try:
Tim Peters208ca702004-08-09 04:12:36 +00001325 # Don't blink! This is where the user's code gets run.
Edward Loper2de91ba2004-08-27 02:07:46 +00001326 exec compile(example.source, filename, "single",
Tim Peters8485b562004-08-04 18:46:34 +00001327 compileflags, 1) in test.globs
Edward Loper2de91ba2004-08-27 02:07:46 +00001328 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001329 exception = None
1330 except KeyboardInterrupt:
1331 raise
1332 except:
1333 exception = sys.exc_info()
Edward Loper2de91ba2004-08-27 02:07:46 +00001334 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001335
Tim Peters208ca702004-08-09 04:12:36 +00001336 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001337 self._fakeout.truncate(0)
1338
1339 # If the example executed without raising any exceptions,
1340 # then verify its output and report its outcome.
1341 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001342 if self._checker.check_output(example.want, got,
1343 self.optionflags):
Edward Lopera89f88d2004-08-26 02:45:51 +00001344 if not quiet:
1345 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001346 else:
Edward Lopera89f88d2004-08-26 02:45:51 +00001347 if not quiet:
1348 self.report_failure(out, test, example, got)
Tim Peters8485b562004-08-04 18:46:34 +00001349 failures += 1
1350
1351 # If the example raised an exception, then check if it was
1352 # expected.
1353 else:
1354 exc_info = sys.exc_info()
1355 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1356
Edward Lopera6b68322004-08-26 00:05:43 +00001357 # If `example.exc_msg` is None, then we weren't
1358 # expecting an exception.
1359 if example.exc_msg is None:
Edward Lopera89f88d2004-08-26 02:45:51 +00001360 if not quiet:
1361 self.report_unexpected_exception(out, test, example,
1362 exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001363 failures += 1
Edward Lopera6b68322004-08-26 00:05:43 +00001364 # If `example.exc_msg` matches the actual exception
1365 # message (`exc_msg`), then the example succeeds.
1366 elif (self._checker.check_output(example.exc_msg, exc_msg,
1367 self.optionflags)):
Edward Lopera89f88d2004-08-26 02:45:51 +00001368 if not quiet:
1369 got += _exception_traceback(exc_info)
1370 self.report_success(out, test, example, got)
Edward Lopera6b68322004-08-26 00:05:43 +00001371 # Otherwise, the example fails.
Tim Peters8485b562004-08-04 18:46:34 +00001372 else:
Edward Lopera89f88d2004-08-26 02:45:51 +00001373 if not quiet:
1374 got += _exception_traceback(exc_info)
1375 self.report_failure(out, test, example, got)
Edward Lopera6b68322004-08-26 00:05:43 +00001376 failures += 1
Tim Peters8485b562004-08-04 18:46:34 +00001377
1378 # Restore the option flags (in case they were modified)
1379 self.optionflags = original_optionflags
1380
1381 # Record and return the number of failures and tries.
1382 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001383 return failures, tries
1384
Tim Peters8485b562004-08-04 18:46:34 +00001385 def __record_outcome(self, test, f, t):
1386 """
1387 Record the fact that the given DocTest (`test`) generated `f`
1388 failures out of `t` tried examples.
1389 """
1390 f2, t2 = self._name2ft.get(test.name, (0,0))
1391 self._name2ft[test.name] = (f+f2, t+t2)
1392 self.failures += f
1393 self.tries += t
1394
Edward Loper2de91ba2004-08-27 02:07:46 +00001395 __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1396 r'(?P<name>[\w\.]+)'
1397 r'\[(?P<examplenum>\d+)\]>$')
1398 def __patched_linecache_getlines(self, filename):
1399 m = self.__LINECACHE_FILENAME_RE.match(filename)
1400 if m and m.group('name') == self.test.name:
1401 example = self.test.examples[int(m.group('examplenum'))]
1402 return example.source.splitlines(True)
1403 else:
1404 return self.save_linecache_getlines(filename)
1405
Tim Peters8485b562004-08-04 18:46:34 +00001406 def run(self, test, compileflags=None, out=None, clear_globs=True):
1407 """
1408 Run the examples in `test`, and display the results using the
1409 writer function `out`.
1410
1411 The examples are run in the namespace `test.globs`. If
1412 `clear_globs` is true (the default), then this namespace will
1413 be cleared after the test runs, to help with garbage
1414 collection. If you would like to examine the namespace after
1415 the test completes, then use `clear_globs=False`.
1416
1417 `compileflags` gives the set of flags that should be used by
1418 the Python compiler when running the examples. If not
1419 specified, then it will default to the set of future-import
1420 flags that apply to `globs`.
1421
1422 The output of each example is checked using
1423 `DocTestRunner.check_output`, and the results are formatted by
1424 the `DocTestRunner.report_*` methods.
1425 """
Edward Loper2de91ba2004-08-27 02:07:46 +00001426 self.test = test
1427
Tim Peters8485b562004-08-04 18:46:34 +00001428 if compileflags is None:
1429 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001430
Tim Peters6c542b72004-08-09 16:43:36 +00001431 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001432 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001433 out = save_stdout.write
1434 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001435
Edward Loper2de91ba2004-08-27 02:07:46 +00001436 # Patch pdb.set_trace to restore sys.stdout during interactive
1437 # debugging (so it's not still redirected to self._fakeout).
1438 # Note that the interactive output will go to *our*
1439 # save_stdout, even if that's not the real sys.stdout; this
1440 # allows us to write test cases for the set_trace behavior.
Tim Peters6c542b72004-08-09 16:43:36 +00001441 save_set_trace = pdb.set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001442 self.debugger = _OutputRedirectingPdb(save_stdout)
1443 self.debugger.reset()
1444 pdb.set_trace = self.debugger.set_trace
1445
1446 # Patch linecache.getlines, so we can see the example's source
1447 # when we're inside the debugger.
1448 self.save_linecache_getlines = linecache.getlines
1449 linecache.getlines = self.__patched_linecache_getlines
1450
Tim Peters8485b562004-08-04 18:46:34 +00001451 try:
Tim Peters8485b562004-08-04 18:46:34 +00001452 return self.__run(test, compileflags, out)
1453 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001454 sys.stdout = save_stdout
1455 pdb.set_trace = save_set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001456 linecache.getlines = self.save_linecache_getlines
Tim Peters8485b562004-08-04 18:46:34 +00001457 if clear_globs:
1458 test.globs.clear()
1459
1460 #/////////////////////////////////////////////////////////////////
1461 # Summarization
1462 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001463 def summarize(self, verbose=None):
1464 """
Tim Peters8485b562004-08-04 18:46:34 +00001465 Print a summary of all the test cases that have been run by
1466 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1467 the total number of failed examples, and `t` is the total
1468 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001469
Tim Peters8485b562004-08-04 18:46:34 +00001470 The optional `verbose` argument controls how detailed the
1471 summary is. If the verbosity is not specified, then the
1472 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001473 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001474 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001475 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001476 notests = []
1477 passed = []
1478 failed = []
1479 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001480 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001481 name, (f, t) = x
1482 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001483 totalt += t
1484 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001485 if t == 0:
1486 notests.append(name)
1487 elif f == 0:
1488 passed.append( (name, t) )
1489 else:
1490 failed.append(x)
1491 if verbose:
1492 if notests:
1493 print len(notests), "items had no tests:"
1494 notests.sort()
1495 for thing in notests:
1496 print " ", thing
1497 if passed:
1498 print len(passed), "items passed all tests:"
1499 passed.sort()
1500 for thing, count in passed:
1501 print " %3d tests in %s" % (count, thing)
1502 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001503 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001504 print len(failed), "items had failures:"
1505 failed.sort()
1506 for thing, (f, t) in failed:
1507 print " %3d of %3d in %s" % (f, t, thing)
1508 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001509 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001510 print totalt - totalf, "passed and", totalf, "failed."
1511 if totalf:
1512 print "***Test Failed***", totalf, "failures."
1513 elif verbose:
1514 print "Test passed."
1515 return totalf, totalt
1516
Edward Loper34fcb142004-08-09 02:45:41 +00001517class OutputChecker:
1518 """
1519 A class used to check the whether the actual output from a doctest
1520 example matches the expected output. `OutputChecker` defines two
1521 methods: `check_output`, which compares a given pair of outputs,
1522 and returns true if they match; and `output_difference`, which
1523 returns a string describing the differences between two outputs.
1524 """
1525 def check_output(self, want, got, optionflags):
1526 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001527 Return True iff the actual output from an example (`got`)
1528 matches the expected output (`want`). These strings are
1529 always considered to match if they are identical; but
1530 depending on what option flags the test runner is using,
1531 several non-exact match types are also possible. See the
1532 documentation for `TestRunner` for more information about
1533 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001534 """
1535 # Handle the common case first, for efficiency:
1536 # if they're string-identical, always return true.
1537 if got == want:
1538 return True
1539
1540 # The values True and False replaced 1 and 0 as the return
1541 # value for boolean comparisons in Python 2.3.
1542 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1543 if (got,want) == ("True\n", "1\n"):
1544 return True
1545 if (got,want) == ("False\n", "0\n"):
1546 return True
1547
1548 # <BLANKLINE> can be used as a special sequence to signify a
1549 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1550 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1551 # Replace <BLANKLINE> in want with a blank line.
1552 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1553 '', want)
1554 # If a line in got contains only spaces, then remove the
1555 # spaces.
1556 got = re.sub('(?m)^\s*?$', '', got)
1557 if got == want:
1558 return True
1559
1560 # This flag causes doctest to ignore any differences in the
1561 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001562 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001563 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001564 got = ' '.join(got.split())
1565 want = ' '.join(want.split())
1566 if got == want:
1567 return True
1568
1569 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001570 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001571 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001572 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001573 return True
1574
1575 # We didn't find any match; return false.
1576 return False
1577
Tim Petersc6cbab02004-08-22 19:43:28 +00001578 # Should we do a fancy diff?
1579 def _do_a_fancy_diff(self, want, got, optionflags):
1580 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001581 if not optionflags & (REPORT_UDIFF |
1582 REPORT_CDIFF |
1583 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001584 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001585
Tim Petersc6cbab02004-08-22 19:43:28 +00001586 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001587 # too hard ... or maybe not. In two real-life failures Tim saw,
1588 # a diff was a major help anyway, so this is commented out.
1589 # [todo] _ellipsis_match() knows which pieces do and don't match,
1590 # and could be the basis for a kick-ass diff in this case.
1591 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1592 ## return False
1593
Tim Petersc6cbab02004-08-22 19:43:28 +00001594 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001595 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001596 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001597 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001598
Tim Petersc6cbab02004-08-22 19:43:28 +00001599 # The other diff types need at least a few lines to be helpful.
1600 return want.count('\n') > 2 and got.count('\n') > 2
1601
Edward Loperca9111e2004-08-26 03:00:24 +00001602 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001603 """
1604 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001605 expected output for a given example (`example`) and the actual
1606 output (`got`). `optionflags` is the set of option flags used
1607 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001608 """
Edward Loperca9111e2004-08-26 03:00:24 +00001609 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001610 # If <BLANKLINE>s are being used, then replace blank lines
1611 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001612 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001613 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001614
Tim Peters5b799c12004-08-26 05:21:59 +00001615 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001616 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001617 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001618 want_lines = want.splitlines(True) # True == keep line ends
1619 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001620 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001621 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001622 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1623 diff = list(diff)[2:] # strip the diff header
1624 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001625 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001626 diff = difflib.context_diff(want_lines, got_lines, n=2)
1627 diff = list(diff)[2:] # strip the diff header
1628 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001629 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001630 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1631 diff = list(engine.compare(want_lines, got_lines))
1632 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001633 else:
1634 assert 0, 'Bad diff option'
1635 # Remove trailing whitespace on diff output.
1636 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001637 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001638
1639 # If we're not using diff, then simply list the expected
1640 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001641 if want and got:
1642 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1643 elif want:
1644 return 'Expected:\n%sGot nothing\n' % _indent(want)
1645 elif got:
1646 return 'Expected nothing\nGot:\n%s' % _indent(got)
1647 else:
1648 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001649
Tim Peters19397e52004-08-06 22:02:59 +00001650class DocTestFailure(Exception):
1651 """A DocTest example has failed in debugging mode.
1652
1653 The exception instance has variables:
1654
1655 - test: the DocTest object being run
1656
1657 - excample: the Example object that failed
1658
1659 - got: the actual output
1660 """
1661 def __init__(self, test, example, got):
1662 self.test = test
1663 self.example = example
1664 self.got = got
1665
1666 def __str__(self):
1667 return str(self.test)
1668
1669class UnexpectedException(Exception):
1670 """A DocTest example has encountered an unexpected exception
1671
1672 The exception instance has variables:
1673
1674 - test: the DocTest object being run
1675
1676 - excample: the Example object that failed
1677
1678 - exc_info: the exception info
1679 """
1680 def __init__(self, test, example, exc_info):
1681 self.test = test
1682 self.example = example
1683 self.exc_info = exc_info
1684
1685 def __str__(self):
1686 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001687
Tim Peters19397e52004-08-06 22:02:59 +00001688class DebugRunner(DocTestRunner):
1689 r"""Run doc tests but raise an exception as soon as there is a failure.
1690
1691 If an unexpected exception occurs, an UnexpectedException is raised.
1692 It contains the test, the example, and the original exception:
1693
1694 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001695 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1696 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001697 >>> try:
1698 ... runner.run(test)
1699 ... except UnexpectedException, failure:
1700 ... pass
1701
1702 >>> failure.test is test
1703 True
1704
1705 >>> failure.example.want
1706 '42\n'
1707
1708 >>> exc_info = failure.exc_info
1709 >>> raise exc_info[0], exc_info[1], exc_info[2]
1710 Traceback (most recent call last):
1711 ...
1712 KeyError
1713
1714 We wrap the original exception to give the calling application
1715 access to the test and example information.
1716
1717 If the output doesn't match, then a DocTestFailure is raised:
1718
Edward Lopera1ef6112004-08-09 16:14:41 +00001719 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001720 ... >>> x = 1
1721 ... >>> x
1722 ... 2
1723 ... ''', {}, 'foo', 'foo.py', 0)
1724
1725 >>> try:
1726 ... runner.run(test)
1727 ... except DocTestFailure, failure:
1728 ... pass
1729
1730 DocTestFailure objects provide access to the test:
1731
1732 >>> failure.test is test
1733 True
1734
1735 As well as to the example:
1736
1737 >>> failure.example.want
1738 '2\n'
1739
1740 and the actual output:
1741
1742 >>> failure.got
1743 '1\n'
1744
1745 If a failure or error occurs, the globals are left intact:
1746
1747 >>> del test.globs['__builtins__']
1748 >>> test.globs
1749 {'x': 1}
1750
Edward Lopera1ef6112004-08-09 16:14:41 +00001751 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001752 ... >>> x = 2
1753 ... >>> raise KeyError
1754 ... ''', {}, 'foo', 'foo.py', 0)
1755
1756 >>> runner.run(test)
1757 Traceback (most recent call last):
1758 ...
1759 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001760
Tim Peters19397e52004-08-06 22:02:59 +00001761 >>> del test.globs['__builtins__']
1762 >>> test.globs
1763 {'x': 2}
1764
1765 But the globals are cleared if there is no error:
1766
Edward Lopera1ef6112004-08-09 16:14:41 +00001767 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001768 ... >>> x = 2
1769 ... ''', {}, 'foo', 'foo.py', 0)
1770
1771 >>> runner.run(test)
1772 (0, 1)
1773
1774 >>> test.globs
1775 {}
1776
1777 """
1778
1779 def run(self, test, compileflags=None, out=None, clear_globs=True):
1780 r = DocTestRunner.run(self, test, compileflags, out, False)
1781 if clear_globs:
1782 test.globs.clear()
1783 return r
1784
1785 def report_unexpected_exception(self, out, test, example, exc_info):
1786 raise UnexpectedException(test, example, exc_info)
1787
1788 def report_failure(self, out, test, example, got):
1789 raise DocTestFailure(test, example, got)
1790
Tim Peters8485b562004-08-04 18:46:34 +00001791######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001792## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001793######################################################################
1794# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001795
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001796def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001797 report=True, optionflags=0, extraglobs=None,
1798 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001799 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001800 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001801
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001802 Test examples in docstrings in functions and classes reachable
1803 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001804 with m.__doc__. Unless isprivate is specified, private names
1805 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001806
1807 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001808 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001809 function and class docstrings are tested even if the name is private;
1810 strings are tested directly, as if they were docstrings.
1811
1812 Return (#failures, #tests).
1813
1814 See doctest.__doc__ for an overview.
1815
1816 Optional keyword arg "name" gives the name of the module; by default
1817 use m.__name__.
1818
1819 Optional keyword arg "globs" gives a dict to be used as the globals
1820 when executing examples; by default, use m.__dict__. A copy of this
1821 dict is actually used for each docstring, so that each docstring's
1822 examples start with a clean slate.
1823
Tim Peters8485b562004-08-04 18:46:34 +00001824 Optional keyword arg "extraglobs" gives a dictionary that should be
1825 merged into the globals that are used to execute examples. By
1826 default, no extra globals are used. This is new in 2.4.
1827
Tim Peters8a7d2d52001-01-16 07:10:57 +00001828 Optional keyword arg "verbose" prints lots of stuff if true, prints
1829 only failures if false; by default, it's true iff "-v" is in sys.argv.
1830
Tim Peters8a7d2d52001-01-16 07:10:57 +00001831 Optional keyword arg "report" prints a summary at the end when true,
1832 else prints nothing at the end. In verbose mode, the summary is
1833 detailed, else very brief (in fact, empty if all tests passed).
1834
Tim Peters6ebe61f2003-06-27 20:48:05 +00001835 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001836 and defaults to 0. This is new in 2.3. Possible values (see the
1837 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001838
1839 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001840 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001841 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001842 ELLIPSIS
Edward Loper71f55af2004-08-26 01:41:51 +00001843 REPORT_UDIFF
1844 REPORT_CDIFF
1845 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001846 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001847
1848 Optional keyword arg "raise_on_error" raises an exception on the
1849 first unexpected exception or failure. This allows failures to be
1850 post-mortem debugged.
1851
Tim Petersf727c6c2004-08-08 01:48:59 +00001852 Deprecated in Python 2.4:
1853 Optional keyword arg "isprivate" specifies a function used to
1854 determine whether a name is private. The default function is
1855 treat all functions as public. Optionally, "isprivate" can be
1856 set to doctest.is_private to skip over functions marked as private
1857 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001858 """
1859
1860 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001861 Advanced tomfoolery: testmod runs methods of a local instance of
1862 class doctest.Tester, then merges the results into (or creates)
1863 global Tester instance doctest.master. Methods of doctest.master
1864 can be called directly too, if you want to do something unusual.
1865 Passing report=0 to testmod is especially useful then, to delay
1866 displaying a summary. Invoke doctest.master.summarize(verbose)
1867 when you're done fiddling.
1868 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001869 if isprivate is not None:
1870 warnings.warn("the isprivate argument is deprecated; "
1871 "examine DocTestFinder.find() lists instead",
1872 DeprecationWarning)
1873
Tim Peters8485b562004-08-04 18:46:34 +00001874 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001875 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001876 # DWA - m will still be None if this wasn't invoked from the command
1877 # line, in which case the following TypeError is about as good an error
1878 # as we should expect
1879 m = sys.modules.get('__main__')
1880
Tim Peters8485b562004-08-04 18:46:34 +00001881 # Check that we were actually given a module.
1882 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001883 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001884
1885 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001886 if name is None:
1887 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001888
1889 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001890 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001891
1892 if raise_on_error:
1893 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1894 else:
1895 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1896
Tim Peters8485b562004-08-04 18:46:34 +00001897 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1898 runner.run(test)
1899
Tim Peters8a7d2d52001-01-16 07:10:57 +00001900 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001901 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001902
Tim Peters8485b562004-08-04 18:46:34 +00001903 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001904
Tim Peters8485b562004-08-04 18:46:34 +00001905def run_docstring_examples(f, globs, verbose=False, name="NoName",
1906 compileflags=None, optionflags=0):
1907 """
1908 Test examples in the given object's docstring (`f`), using `globs`
1909 as globals. Optional argument `name` is used in failure messages.
1910 If the optional argument `verbose` is true, then generate output
1911 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001912
Tim Peters8485b562004-08-04 18:46:34 +00001913 `compileflags` gives the set of flags that should be used by the
1914 Python compiler when running the examples. If not specified, then
1915 it will default to the set of future-import flags that apply to
1916 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001917
Tim Peters8485b562004-08-04 18:46:34 +00001918 Optional keyword arg `optionflags` specifies options for the
1919 testing and output. See the documentation for `testmod` for more
1920 information.
1921 """
1922 # Find, parse, and run all tests in the given module.
1923 finder = DocTestFinder(verbose=verbose, recurse=False)
1924 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1925 for test in finder.find(f, name, globs=globs):
1926 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001927
Tim Peters8485b562004-08-04 18:46:34 +00001928######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001929## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001930######################################################################
1931# This is provided only for backwards compatibility. It's not
1932# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001933
Tim Peters8485b562004-08-04 18:46:34 +00001934class Tester:
1935 def __init__(self, mod=None, globs=None, verbose=None,
1936 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001937
1938 warnings.warn("class Tester is deprecated; "
1939 "use class doctest.DocTestRunner instead",
1940 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001941 if mod is None and globs is None:
1942 raise TypeError("Tester.__init__: must specify mod or globs")
1943 if mod is not None and not _ismodule(mod):
1944 raise TypeError("Tester.__init__: mod must be a module; %r" %
1945 (mod,))
1946 if globs is None:
1947 globs = mod.__dict__
1948 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001949
Tim Peters8485b562004-08-04 18:46:34 +00001950 self.verbose = verbose
1951 self.isprivate = isprivate
1952 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001953 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001954 self.testrunner = DocTestRunner(verbose=verbose,
1955 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001956
Tim Peters8485b562004-08-04 18:46:34 +00001957 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001958 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001959 if self.verbose:
1960 print "Running string", name
1961 (f,t) = self.testrunner.run(test)
1962 if self.verbose:
1963 print f, "of", t, "examples failed in string", name
1964 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001965
Tim Petersf3f57472004-08-08 06:11:48 +00001966 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001967 f = t = 0
1968 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001969 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001970 for test in tests:
1971 (f2, t2) = self.testrunner.run(test)
1972 (f,t) = (f+f2, t+t2)
1973 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001974
Tim Peters8485b562004-08-04 18:46:34 +00001975 def rundict(self, d, name, module=None):
1976 import new
1977 m = new.module(name)
1978 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001979 if module is None:
1980 module = False
1981 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001982
Tim Peters8485b562004-08-04 18:46:34 +00001983 def run__test__(self, d, name):
1984 import new
1985 m = new.module(name)
1986 m.__test__ = d
1987 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001988
Tim Peters8485b562004-08-04 18:46:34 +00001989 def summarize(self, verbose=None):
1990 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001991
Tim Peters8485b562004-08-04 18:46:34 +00001992 def merge(self, other):
1993 d = self.testrunner._name2ft
1994 for name, (f, t) in other.testrunner._name2ft.items():
1995 if name in d:
1996 print "*** Tester.merge: '" + name + "' in both" \
1997 " testers; summing outcomes."
1998 f2, t2 = d[name]
1999 f = f + f2
2000 t = t + t2
2001 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00002002
Tim Peters8485b562004-08-04 18:46:34 +00002003######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002004## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002005######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002006
Jim Fultonf54bad42004-08-28 14:57:56 +00002007_unittest_reportflags = 0
Tim Peters38330fe2004-08-30 16:19:24 +00002008
Jim Fultonf54bad42004-08-28 14:57:56 +00002009def set_unittest_reportflags(flags):
Tim Peters38330fe2004-08-30 16:19:24 +00002010 """Sets the unittest option flags.
Jim Fultonf54bad42004-08-28 14:57:56 +00002011
2012 The old flag is returned so that a runner could restore the old
2013 value if it wished to:
2014
2015 >>> old = _unittest_reportflags
2016 >>> set_unittest_reportflags(REPORT_NDIFF |
2017 ... REPORT_ONLY_FIRST_FAILURE) == old
2018 True
2019
2020 >>> import doctest
2021 >>> doctest._unittest_reportflags == (REPORT_NDIFF |
2022 ... REPORT_ONLY_FIRST_FAILURE)
2023 True
Tim Petersdf7a2082004-08-29 00:38:17 +00002024
Jim Fultonf54bad42004-08-28 14:57:56 +00002025 Only reporting flags can be set:
2026
2027 >>> set_unittest_reportflags(ELLIPSIS)
2028 Traceback (most recent call last):
2029 ...
Tim Peters38330fe2004-08-30 16:19:24 +00002030 ValueError: ('Only reporting flags allowed', 8)
Jim Fultonf54bad42004-08-28 14:57:56 +00002031
2032 >>> set_unittest_reportflags(old) == (REPORT_NDIFF |
2033 ... REPORT_ONLY_FIRST_FAILURE)
2034 True
Jim Fultonf54bad42004-08-28 14:57:56 +00002035 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002036 global _unittest_reportflags
Tim Peters38330fe2004-08-30 16:19:24 +00002037
2038 if (flags & REPORTING_FLAGS) != flags:
2039 raise ValueError("Only reporting flags allowed", flags)
Jim Fultonf54bad42004-08-28 14:57:56 +00002040 old = _unittest_reportflags
2041 _unittest_reportflags = flags
2042 return old
Tim Petersdf7a2082004-08-29 00:38:17 +00002043
Jim Fultonf54bad42004-08-28 14:57:56 +00002044
Tim Peters19397e52004-08-06 22:02:59 +00002045class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002046
Edward Loper34fcb142004-08-09 02:45:41 +00002047 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2048 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002049
Jim Fultona643b652004-07-14 19:06:50 +00002050 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002051 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002052 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002053 self._dt_test = test
2054 self._dt_setUp = setUp
2055 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002056
Jim Fultona643b652004-07-14 19:06:50 +00002057 def setUp(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002058 test = self._dt_test
Tim Petersdf7a2082004-08-29 00:38:17 +00002059
Tim Peters19397e52004-08-06 22:02:59 +00002060 if self._dt_setUp is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002061 self._dt_setUp(test)
Jim Fultona643b652004-07-14 19:06:50 +00002062
2063 def tearDown(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002064 test = self._dt_test
2065
Tim Peters19397e52004-08-06 22:02:59 +00002066 if self._dt_tearDown is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002067 self._dt_tearDown(test)
2068
2069 test.globs.clear()
Jim Fultona643b652004-07-14 19:06:50 +00002070
2071 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002072 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002073 old = sys.stdout
2074 new = StringIO()
Jim Fultonf54bad42004-08-28 14:57:56 +00002075 optionflags = self._dt_optionflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002076
Tim Peters38330fe2004-08-30 16:19:24 +00002077 if not (optionflags & REPORTING_FLAGS):
Jim Fultonf54bad42004-08-28 14:57:56 +00002078 # The option flags don't include any reporting flags,
2079 # so add the default reporting flags
2080 optionflags |= _unittest_reportflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002081
Jim Fultonf54bad42004-08-28 14:57:56 +00002082 runner = DocTestRunner(optionflags=optionflags,
Edward Loper34fcb142004-08-09 02:45:41 +00002083 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002084
Jim Fultona643b652004-07-14 19:06:50 +00002085 try:
Tim Peters19397e52004-08-06 22:02:59 +00002086 runner.DIVIDER = "-"*70
Jim Fultonf54bad42004-08-28 14:57:56 +00002087 failures, tries = runner.run(
2088 test, out=new.write, clear_globs=False)
Jim Fultona643b652004-07-14 19:06:50 +00002089 finally:
2090 sys.stdout = old
2091
2092 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002093 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002094
Tim Peters19397e52004-08-06 22:02:59 +00002095 def format_failure(self, err):
2096 test = self._dt_test
2097 if test.lineno is None:
2098 lineno = 'unknown line number'
2099 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002100 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002101 lname = '.'.join(test.name.split('.')[-1:])
2102 return ('Failed doctest test for %s\n'
2103 ' File "%s", line %s, in %s\n\n%s'
2104 % (test.name, test.filename, lineno, lname, err)
2105 )
2106
2107 def debug(self):
2108 r"""Run the test case without results and without catching exceptions
2109
2110 The unit test framework includes a debug method on test cases
2111 and test suites to support post-mortem debugging. The test code
2112 is run in such a way that errors are not caught. This way a
2113 caller can catch the errors and initiate post-mortem debugging.
2114
2115 The DocTestCase provides a debug method that raises
2116 UnexpectedException errors if there is an unexepcted
2117 exception:
2118
Edward Lopera1ef6112004-08-09 16:14:41 +00002119 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002120 ... {}, 'foo', 'foo.py', 0)
2121 >>> case = DocTestCase(test)
2122 >>> try:
2123 ... case.debug()
2124 ... except UnexpectedException, failure:
2125 ... pass
2126
2127 The UnexpectedException contains the test, the example, and
2128 the original exception:
2129
2130 >>> failure.test is test
2131 True
2132
2133 >>> failure.example.want
2134 '42\n'
2135
2136 >>> exc_info = failure.exc_info
2137 >>> raise exc_info[0], exc_info[1], exc_info[2]
2138 Traceback (most recent call last):
2139 ...
2140 KeyError
2141
2142 If the output doesn't match, then a DocTestFailure is raised:
2143
Edward Lopera1ef6112004-08-09 16:14:41 +00002144 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002145 ... >>> x = 1
2146 ... >>> x
2147 ... 2
2148 ... ''', {}, 'foo', 'foo.py', 0)
2149 >>> case = DocTestCase(test)
2150
2151 >>> try:
2152 ... case.debug()
2153 ... except DocTestFailure, failure:
2154 ... pass
2155
2156 DocTestFailure objects provide access to the test:
2157
2158 >>> failure.test is test
2159 True
2160
2161 As well as to the example:
2162
2163 >>> failure.example.want
2164 '2\n'
2165
2166 and the actual output:
2167
2168 >>> failure.got
2169 '1\n'
2170
2171 """
2172
Jim Fultonf54bad42004-08-28 14:57:56 +00002173 self.setUp()
Edward Loper34fcb142004-08-09 02:45:41 +00002174 runner = DebugRunner(optionflags=self._dt_optionflags,
2175 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002176 runner.run(self._dt_test)
Jim Fultonf54bad42004-08-28 14:57:56 +00002177 self.tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002178
2179 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002180 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002181
2182 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002183 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002184 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2185
2186 __str__ = __repr__
2187
2188 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002189 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002190
Jim Fultonf54bad42004-08-28 14:57:56 +00002191def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2192 **options):
Tim Peters8485b562004-08-04 18:46:34 +00002193 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002194 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002195
Tim Peters19397e52004-08-06 22:02:59 +00002196 This converts each documentation string in a module that
2197 contains doctest tests to a unittest test case. If any of the
2198 tests in a doc string fail, then the test case fails. An exception
2199 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002200 (sometimes approximate) line number.
2201
Tim Peters19397e52004-08-06 22:02:59 +00002202 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002203 can be either a module or a module name.
2204
2205 If no argument is given, the calling module is used.
Jim Fultonf54bad42004-08-28 14:57:56 +00002206
2207 A number of options may be provided as keyword arguments:
2208
2209 package
2210 The name of a Python package. Text-file paths will be
2211 interpreted relative to the directory containing this package.
2212 The package may be supplied as a package object or as a dotted
2213 package name.
2214
2215 setUp
2216 The name of a set-up function. This is called before running the
2217 tests in each file. The setUp function will be passed a DocTest
2218 object. The setUp function can access the test globals as the
2219 globs attribute of the test passed.
2220
2221 tearDown
2222 The name of a tear-down function. This is called after running the
2223 tests in each file. The tearDown function will be passed a DocTest
2224 object. The tearDown function can access the test globals as the
2225 globs attribute of the test passed.
2226
2227 globs
2228 A dictionary containing initial global variables for the tests.
2229
2230 optionflags
2231 A set of doctest option flags expressed as an integer.
Jim Fultona643b652004-07-14 19:06:50 +00002232 """
Jim Fultona643b652004-07-14 19:06:50 +00002233
Tim Peters8485b562004-08-04 18:46:34 +00002234 if test_finder is None:
2235 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002236
Tim Peters19397e52004-08-06 22:02:59 +00002237 module = _normalize_module(module)
2238 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2239 if globs is None:
2240 globs = module.__dict__
Jim Fultonf54bad42004-08-28 14:57:56 +00002241 if not tests:
2242 # Why do we want to do this? Because it reveals a bug that might
2243 # otherwise be hidden.
Tim Peters19397e52004-08-06 22:02:59 +00002244 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002245
2246 tests.sort()
2247 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002248 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002249 if len(test.examples) == 0:
2250 continue
Tim Peters8485b562004-08-04 18:46:34 +00002251 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002252 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002253 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002254 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002255 test.filename = filename
Jim Fultonf54bad42004-08-28 14:57:56 +00002256 suite.addTest(DocTestCase(test, **options))
Tim Peters19397e52004-08-06 22:02:59 +00002257
2258 return suite
2259
2260class DocFileCase(DocTestCase):
2261
2262 def id(self):
2263 return '_'.join(self._dt_test.name.split('.'))
2264
2265 def __repr__(self):
2266 return self._dt_test.filename
2267 __str__ = __repr__
2268
2269 def format_failure(self, err):
2270 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2271 % (self._dt_test.name, self._dt_test.filename, err)
2272 )
2273
Jim Fultonf54bad42004-08-28 14:57:56 +00002274def DocFileTest(path, package=None, globs=None, **options):
Tim Peters19397e52004-08-06 22:02:59 +00002275 package = _normalize_module(package)
2276 name = path.split('/')[-1]
2277 dir = os.path.split(package.__file__)[0]
2278 path = os.path.join(dir, *(path.split('/')))
2279 doc = open(path).read()
2280
2281 if globs is None:
2282 globs = {}
2283
Edward Lopera1ef6112004-08-09 16:14:41 +00002284 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002285
Jim Fultonf54bad42004-08-28 14:57:56 +00002286 return DocFileCase(test, **options)
Tim Peters19397e52004-08-06 22:02:59 +00002287
2288def DocFileSuite(*paths, **kw):
2289 """Creates a suite of doctest files.
2290
2291 One or more text file paths are given as strings. These should
2292 use "/" characters to separate path segments. Paths are relative
2293 to the directory of the calling module, or relative to the package
2294 passed as a keyword argument.
2295
2296 A number of options may be provided as keyword arguments:
2297
2298 package
2299 The name of a Python package. Text-file paths will be
2300 interpreted relative to the directory containing this package.
2301 The package may be supplied as a package object or as a dotted
2302 package name.
2303
2304 setUp
2305 The name of a set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002306 tests in each file. The setUp function will be passed a DocTest
2307 object. The setUp function can access the test globals as the
2308 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002309
2310 tearDown
2311 The name of a tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002312 tests in each file. The tearDown function will be passed a DocTest
2313 object. The tearDown function can access the test globals as the
2314 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002315
2316 globs
2317 A dictionary containing initial global variables for the tests.
Jim Fultonf54bad42004-08-28 14:57:56 +00002318
2319 optionflags
2320 A set of doctest option flags expressed as an integer.
Tim Petersdf7a2082004-08-29 00:38:17 +00002321
Tim Peters19397e52004-08-06 22:02:59 +00002322 """
2323 suite = unittest.TestSuite()
2324
2325 # We do this here so that _normalize_module is called at the right
2326 # level. If it were called in DocFileTest, then this function
2327 # would be the caller and we might guess the package incorrectly.
2328 kw['package'] = _normalize_module(kw.get('package'))
2329
2330 for path in paths:
2331 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002332
Tim Petersdb3756d2003-06-29 05:30:48 +00002333 return suite
2334
Tim Peters8485b562004-08-04 18:46:34 +00002335######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002336## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002337######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002338
Tim Peters19397e52004-08-06 22:02:59 +00002339def script_from_examples(s):
2340 r"""Extract script from text with examples.
2341
2342 Converts text with examples to a Python script. Example input is
2343 converted to regular code. Example output and all other words
2344 are converted to comments:
2345
2346 >>> text = '''
2347 ... Here are examples of simple math.
2348 ...
2349 ... Python has super accurate integer addition
2350 ...
2351 ... >>> 2 + 2
2352 ... 5
2353 ...
2354 ... And very friendly error messages:
2355 ...
2356 ... >>> 1/0
2357 ... To Infinity
2358 ... And
2359 ... Beyond
2360 ...
2361 ... You can use logic if you want:
2362 ...
2363 ... >>> if 0:
2364 ... ... blah
2365 ... ... blah
2366 ... ...
2367 ...
2368 ... Ho hum
2369 ... '''
2370
2371 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002372 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002373 #
Edward Lopera5db6002004-08-12 02:41:30 +00002374 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002375 #
2376 2 + 2
2377 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002378 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002379 #
Edward Lopera5db6002004-08-12 02:41:30 +00002380 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002381 #
2382 1/0
2383 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002384 ## To Infinity
2385 ## And
2386 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002387 #
Edward Lopera5db6002004-08-12 02:41:30 +00002388 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002389 #
2390 if 0:
2391 blah
2392 blah
Tim Peters19397e52004-08-06 22:02:59 +00002393 #
Edward Lopera5db6002004-08-12 02:41:30 +00002394 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002395 """
Edward Loper00f8da72004-08-26 18:05:07 +00002396 output = []
2397 for piece in DocTestParser().parse(s):
2398 if isinstance(piece, Example):
2399 # Add the example's source code (strip trailing NL)
2400 output.append(piece.source[:-1])
2401 # Add the expected output:
2402 want = piece.want
2403 if want:
2404 output.append('# Expected:')
2405 output += ['## '+l for l in want.split('\n')[:-1]]
2406 else:
2407 # Add non-example text.
2408 output += [_comment_line(l)
2409 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002410
Edward Loper00f8da72004-08-26 18:05:07 +00002411 # Trim junk on both ends.
2412 while output and output[-1] == '#':
2413 output.pop()
2414 while output and output[0] == '#':
2415 output.pop(0)
2416 # Combine the output, and return it.
2417 return '\n'.join(output)
Tim Petersdb3756d2003-06-29 05:30:48 +00002418
2419def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002420 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002421
2422 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002423 test to be debugged and the name (within the module) of the object
2424 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002425 """
Tim Peters8485b562004-08-04 18:46:34 +00002426 module = _normalize_module(module)
2427 tests = DocTestFinder().find(module)
2428 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002429 if not test:
2430 raise ValueError(name, "not found in tests")
2431 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002432 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002433 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002434
Jim Fultona643b652004-07-14 19:06:50 +00002435def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002436 """Debug a single doctest docstring, in argument `src`'"""
2437 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002438 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002439
Jim Fultona643b652004-07-14 19:06:50 +00002440def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002441 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002442 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002443
Tim Petersb6a04d62004-08-23 21:37:56 +00002444 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2445 # docs say, a file so created cannot be opened by name a second time
2446 # on modern Windows boxes, and execfile() needs to open it.
2447 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002448 f = open(srcfilename, 'w')
2449 f.write(src)
2450 f.close()
2451
Tim Petersb6a04d62004-08-23 21:37:56 +00002452 try:
2453 if globs:
2454 globs = globs.copy()
2455 else:
2456 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002457
Tim Petersb6a04d62004-08-23 21:37:56 +00002458 if pm:
2459 try:
2460 execfile(srcfilename, globs, globs)
2461 except:
2462 print sys.exc_info()[1]
2463 pdb.post_mortem(sys.exc_info()[2])
2464 else:
2465 # Note that %r is vital here. '%s' instead can, e.g., cause
2466 # backslashes to get treated as metacharacters on Windows.
2467 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2468
2469 finally:
2470 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002471
Jim Fultona643b652004-07-14 19:06:50 +00002472def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002473 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002474
2475 Provide the module (or dotted name of the module) containing the
2476 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002477 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002478 """
Tim Peters8485b562004-08-04 18:46:34 +00002479 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002480 testsrc = testsource(module, name)
2481 debug_script(testsrc, pm, module.__dict__)
2482
Tim Peters8485b562004-08-04 18:46:34 +00002483######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002484## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002485######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002486class _TestClass:
2487 """
2488 A pointless class, for sanity-checking of docstring testing.
2489
2490 Methods:
2491 square()
2492 get()
2493
2494 >>> _TestClass(13).get() + _TestClass(-12).get()
2495 1
2496 >>> hex(_TestClass(13).square().get())
2497 '0xa9'
2498 """
2499
2500 def __init__(self, val):
2501 """val -> _TestClass object with associated value val.
2502
2503 >>> t = _TestClass(123)
2504 >>> print t.get()
2505 123
2506 """
2507
2508 self.val = val
2509
2510 def square(self):
2511 """square() -> square TestClass's associated value
2512
2513 >>> _TestClass(13).square().get()
2514 169
2515 """
2516
2517 self.val = self.val ** 2
2518 return self
2519
2520 def get(self):
2521 """get() -> return TestClass's associated value.
2522
2523 >>> x = _TestClass(-42)
2524 >>> print x.get()
2525 -42
2526 """
2527
2528 return self.val
2529
2530__test__ = {"_TestClass": _TestClass,
2531 "string": r"""
2532 Example of a string object, searched as-is.
2533 >>> x = 1; y = 2
2534 >>> x + y, x * y
2535 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002536 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002537
Tim Peters6ebe61f2003-06-27 20:48:05 +00002538 "bool-int equivalence": r"""
2539 In 2.2, boolean expressions displayed
2540 0 or 1. By default, we still accept
2541 them. This can be disabled by passing
2542 DONT_ACCEPT_TRUE_FOR_1 to the new
2543 optionflags argument.
2544 >>> 4 == 4
2545 1
2546 >>> 4 == 4
2547 True
2548 >>> 4 > 4
2549 0
2550 >>> 4 > 4
2551 False
2552 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002553
Tim Peters8485b562004-08-04 18:46:34 +00002554 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002555 Blank lines can be marked with <BLANKLINE>:
2556 >>> print 'foo\n\nbar\n'
2557 foo
2558 <BLANKLINE>
2559 bar
2560 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002561 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002562
2563 "ellipsis": r"""
2564 If the ellipsis flag is used, then '...' can be used to
2565 elide substrings in the desired output:
2566 >>> print range(1000) #doctest: +ELLIPSIS
2567 [0, 1, 2, ..., 999]
2568 """,
2569
2570 "whitespace normalization": r"""
2571 If the whitespace normalization flag is used, then
2572 differences in whitespace are ignored.
2573 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2574 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2575 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2576 27, 28, 29]
2577 """,
2578 }
Tim Peters8485b562004-08-04 18:46:34 +00002579
Tim Peters8a7d2d52001-01-16 07:10:57 +00002580def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002581 r = unittest.TextTestRunner()
2582 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002583
2584if __name__ == "__main__":
2585 _test()