blob: dfa18480a7beae57ed45a9a6b444d17acd03cda0 [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',
179 'UNIFIED_DIFF',
180 'CONTEXT_DIFF',
Tim Petersc6cbab02004-08-22 19:43:28 +0000181 'NDIFF_DIFF',
Edward Loperb7503ff2004-08-19 19:19:03 +0000182 # 1. Utility Functions
Tim Peters8485b562004-08-04 18:46:34 +0000183 'is_private',
Edward Loperb7503ff2004-08-19 19:19:03 +0000184 # 2. Example & DocTest
Tim Peters8485b562004-08-04 18:46:34 +0000185 'Example',
186 'DocTest',
Edward Loperb7503ff2004-08-19 19:19:03 +0000187 # 3. Doctest Parser
188 'DocTestParser',
189 # 4. Doctest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000190 'DocTestFinder',
Edward Loperb7503ff2004-08-19 19:19:03 +0000191 # 5. Doctest Runner
Tim Peters8485b562004-08-04 18:46:34 +0000192 'DocTestRunner',
Edward Loperb7503ff2004-08-19 19:19:03 +0000193 'OutputChecker',
194 'DocTestFailure',
195 'UnexpectedException',
196 'DebugRunner',
197 # 6. Test Functions
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000198 'testmod',
199 'run_docstring_examples',
Edward Loperb7503ff2004-08-19 19:19:03 +0000200 # 7. Tester
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000201 'Tester',
Edward Loperb7503ff2004-08-19 19:19:03 +0000202 # 8. Unittest Support
Tim Peters19397e52004-08-06 22:02:59 +0000203 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000204 'DocTestSuite',
Edward Loperb7503ff2004-08-19 19:19:03 +0000205 'DocFileCase',
206 'DocFileTest',
207 'DocFileSuite',
208 # 9. Debugging Support
209 'script_from_examples',
Tim Petersdb3756d2003-06-29 05:30:48 +0000210 'testsource',
Edward Loperb7503ff2004-08-19 19:19:03 +0000211 'debug_src',
212 'debug_script',
Tim Petersdb3756d2003-06-29 05:30:48 +0000213 'debug',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000214]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000215
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000216import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000217
Tim Peters19397e52004-08-06 22:02:59 +0000218import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000219import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000220import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000221from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000222
Tim Petersdd50cb72004-08-23 22:42:55 +0000223# Don't whine about the deprecated is_private function in this
224# module's tests.
225warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
226 __name__, 0)
227
Jim Fulton356fd192004-08-09 11:34:47 +0000228real_pdb_set_trace = pdb.set_trace
229
Tim Peters19397e52004-08-06 22:02:59 +0000230# There are 4 basic classes:
231# - Example: a <source, want> pair, plus an intra-docstring line number.
232# - DocTest: a collection of examples, parsed from a docstring, plus
233# info about where the docstring came from (name, filename, lineno).
234# - DocTestFinder: extracts DocTests from a given object's docstring and
235# its contained objects' docstrings.
236# - DocTestRunner: runs DocTest cases, and accumulates statistics.
237#
238# So the basic picture is:
239#
240# list of:
241# +------+ +---------+ +-------+
242# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
243# +------+ +---------+ +-------+
244# | Example |
245# | ... |
246# | Example |
247# +---------+
248
Edward Loperac20f572004-08-12 02:02:24 +0000249# Option constants.
250OPTIONFLAGS_BY_NAME = {}
251def register_optionflag(name):
252 flag = 1 << len(OPTIONFLAGS_BY_NAME)
253 OPTIONFLAGS_BY_NAME[name] = flag
254 return flag
255
256DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
257DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
258NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
259ELLIPSIS = register_optionflag('ELLIPSIS')
260UNIFIED_DIFF = register_optionflag('UNIFIED_DIFF')
261CONTEXT_DIFF = register_optionflag('CONTEXT_DIFF')
Tim Petersc6cbab02004-08-22 19:43:28 +0000262NDIFF_DIFF = register_optionflag('NDIFF_DIFF')
Edward Loperac20f572004-08-12 02:02:24 +0000263
264# Special string markers for use in `want` strings:
265BLANKLINE_MARKER = '<BLANKLINE>'
266ELLIPSIS_MARKER = '...'
267
Tim Peters8485b562004-08-04 18:46:34 +0000268######################################################################
269## Table of Contents
270######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000271# 1. Utility Functions
272# 2. Example & DocTest -- store test cases
273# 3. DocTest Parser -- extracts examples from strings
274# 4. DocTest Finder -- extracts test cases from objects
275# 5. DocTest Runner -- runs test cases
276# 6. Test Functions -- convenient wrappers for testing
277# 7. Tester Class -- for backwards compatibility
278# 8. Unittest Support
279# 9. Debugging Support
280# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000281
Tim Peters8485b562004-08-04 18:46:34 +0000282######################################################################
283## 1. Utility Functions
284######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000285
286def is_private(prefix, base):
287 """prefix, base -> true iff name prefix + "." + base is "private".
288
289 Prefix may be an empty string, and base does not contain a period.
290 Prefix is ignored (although functions you write conforming to this
291 protocol may make use of it).
292 Return true iff base begins with an (at least one) underscore, but
293 does not both begin and end with (at least) two underscores.
294
295 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000296 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000297 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000298 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000299 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000300 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000301 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000302 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000303 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000304 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000305 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000306 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000307 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000308 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000309 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000310 warnings.warn("is_private is deprecated; it wasn't useful; "
311 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000312 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000313 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
314
Tim Peters8485b562004-08-04 18:46:34 +0000315def _extract_future_flags(globs):
316 """
317 Return the compiler-flags associated with the future features that
318 have been imported into the given namespace (globs).
319 """
320 flags = 0
321 for fname in __future__.all_feature_names:
322 feature = globs.get(fname, None)
323 if feature is getattr(__future__, fname):
324 flags |= feature.compiler_flag
325 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000326
Tim Peters8485b562004-08-04 18:46:34 +0000327def _normalize_module(module, depth=2):
328 """
329 Return the module specified by `module`. In particular:
330 - If `module` is a module, then return module.
331 - If `module` is a string, then import and return the
332 module with that name.
333 - If `module` is None, then return the calling module.
334 The calling module is assumed to be the module of
335 the stack frame at the given depth in the call stack.
336 """
337 if inspect.ismodule(module):
338 return module
339 elif isinstance(module, (str, unicode)):
340 return __import__(module, globals(), locals(), ["*"])
341 elif module is None:
342 return sys.modules[sys._getframe(depth).f_globals['__name__']]
343 else:
344 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000345
Edward Loperaacf0832004-08-26 01:19:50 +0000346def _indent(s, indent=4):
Tim Peters8485b562004-08-04 18:46:34 +0000347 """
Edward Loperaacf0832004-08-26 01:19:50 +0000348 Add the given number of space characters to the beginning every
349 non-blank line in `s`, and return the result.
Tim Peters8485b562004-08-04 18:46:34 +0000350 """
Edward Loperaacf0832004-08-26 01:19:50 +0000351 # This regexp matches the start of non-blank lines:
352 return re.sub('(?m)^(?!$)', indent*' ', s)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000353
Edward Loper8e4a34b2004-08-12 02:34:27 +0000354def _exception_traceback(exc_info):
355 """
356 Return a string containing a traceback message for the given
357 exc_info tuple (as returned by sys.exc_info()).
358 """
359 # Get a traceback message.
360 excout = StringIO()
361 exc_type, exc_val, exc_tb = exc_info
362 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
363 return excout.getvalue()
364
Tim Peters8485b562004-08-04 18:46:34 +0000365# Override some StringIO methods.
366class _SpoofOut(StringIO):
367 def getvalue(self):
368 result = StringIO.getvalue(self)
369 # If anything at all was written, make sure there's a trailing
370 # newline. There's no way for the expected output to indicate
371 # that a trailing newline is missing.
372 if result and not result.endswith("\n"):
373 result += "\n"
374 # Prevent softspace from screwing up the next test case, in
375 # case they used print with a trailing comma in an example.
376 if hasattr(self, "softspace"):
377 del self.softspace
378 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000379
Tim Peters8485b562004-08-04 18:46:34 +0000380 def truncate(self, size=None):
381 StringIO.truncate(self, size)
382 if hasattr(self, "softspace"):
383 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000384
Tim Peters26b3ebb2004-08-19 08:10:08 +0000385# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000386def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000387 """
388 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000389 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000390 False
391 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000392 if ELLIPSIS_MARKER not in want:
393 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000394
Tim Peters26b3ebb2004-08-19 08:10:08 +0000395 # Find "the real" strings.
396 ws = want.split(ELLIPSIS_MARKER)
397 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000398
Tim Petersdc5de3b2004-08-19 14:06:20 +0000399 # Deal with exact matches possibly needed at one or both ends.
400 startpos, endpos = 0, len(got)
401 w = ws[0]
402 if w: # starts with exact match
403 if got.startswith(w):
404 startpos = len(w)
405 del ws[0]
406 else:
407 return False
408 w = ws[-1]
409 if w: # ends with exact match
410 if got.endswith(w):
411 endpos -= len(w)
412 del ws[-1]
413 else:
414 return False
415
416 if startpos > endpos:
417 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000418 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000419 return False
420
421 # For the rest, we only need to find the leftmost non-overlapping
422 # match for each piece. If there's no overall match that way alone,
423 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000424 for w in ws:
425 # w may be '' at times, if there are consecutive ellipses, or
426 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000427 # Search for an empty string succeeds, and doesn't change startpos.
428 startpos = got.find(w, startpos, endpos)
429 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000430 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000431 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000432
Tim Petersdc5de3b2004-08-19 14:06:20 +0000433 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000434
Tim Peters8485b562004-08-04 18:46:34 +0000435######################################################################
436## 2. Example & DocTest
437######################################################################
438## - An "example" is a <source, want> pair, where "source" is a
439## fragment of source code, and "want" is the expected output for
440## "source." The Example class also includes information about
441## where the example was extracted from.
442##
Edward Lopera1ef6112004-08-09 16:14:41 +0000443## - A "doctest" is a collection of examples, typically extracted from
444## a string (such as an object's docstring). The DocTest class also
445## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000446
Tim Peters8485b562004-08-04 18:46:34 +0000447class Example:
448 """
449 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000450 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000451
Edward Loper74bca7a2004-08-12 02:27:44 +0000452 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000453 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000454
Edward Loper74bca7a2004-08-12 02:27:44 +0000455 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000456 from stdout, or a traceback in case of exception). `want` ends
457 with a newline unless it's empty, in which case it's an empty
458 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000459
Edward Lopera6b68322004-08-26 00:05:43 +0000460 - exc_msg: The exception message generated by the example, if
461 the example is expected to generate an exception; or `None` if
462 it is not expected to generate an exception. This exception
463 message is compared against the return value of
464 `traceback.format_exception_only()`. `exc_msg` ends with a
465 newline unless it's `None`. The constructor adds a newline
466 if needed.
467
Edward Loper74bca7a2004-08-12 02:27:44 +0000468 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000469 this Example where the Example begins. This line number is
470 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000471
472 - indent: The example's indentation in the DocTest string.
473 I.e., the number of space characters that preceed the
474 example's first prompt.
475
476 - options: A dictionary mapping from option flags to True or
477 False, which is used to override default options for this
478 example. Any option flags not contained in this dictionary
479 are left at their default value (as specified by the
480 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000481 """
Edward Lopera6b68322004-08-26 00:05:43 +0000482 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
483 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000484 # Normalize inputs.
485 if not source.endswith('\n'):
486 source += '\n'
487 if want and not want.endswith('\n'):
488 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000489 if exc_msg is not None and not exc_msg.endswith('\n'):
490 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000491 # Store properties.
492 self.source = source
493 self.want = want
494 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000495 self.indent = indent
496 if options is None: options = {}
497 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000498 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000499
Tim Peters8485b562004-08-04 18:46:34 +0000500class DocTest:
501 """
502 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000503 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000504
Tim Peters8485b562004-08-04 18:46:34 +0000505 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000506
Tim Peters8485b562004-08-04 18:46:34 +0000507 - globs: The namespace (aka globals) that the examples should
508 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000509
Tim Peters8485b562004-08-04 18:46:34 +0000510 - name: A name identifying the DocTest (typically, the name of
511 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000512
Tim Peters8485b562004-08-04 18:46:34 +0000513 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000514 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000515
Tim Peters8485b562004-08-04 18:46:34 +0000516 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000517 begins, or `None` if the line number is unavailable. This
518 line number is zero-based, with respect to the beginning of
519 the file.
520
521 - docstring: The string that the examples were extracted from,
522 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000523 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000524 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000525 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000526 Create a new DocTest containing the given examples. The
527 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000528 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000529 assert not isinstance(examples, basestring), \
530 "DocTest no longer accepts str; use DocTestParser instead"
531 self.examples = examples
532 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000533 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000534 self.name = name
535 self.filename = filename
536 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000537
538 def __repr__(self):
539 if len(self.examples) == 0:
540 examples = 'no examples'
541 elif len(self.examples) == 1:
542 examples = '1 example'
543 else:
544 examples = '%d examples' % len(self.examples)
545 return ('<DocTest %s from %s:%s (%s)>' %
546 (self.name, self.filename, self.lineno, examples))
547
548
549 # This lets us sort tests by name:
550 def __cmp__(self, other):
551 if not isinstance(other, DocTest):
552 return -1
553 return cmp((self.name, self.filename, self.lineno, id(self)),
554 (other.name, other.filename, other.lineno, id(other)))
555
556######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000557## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000558######################################################################
559
Edward Lopera1ef6112004-08-09 16:14:41 +0000560class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000561 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000562 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000563 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000564 # This regular expression is used to find doctest examples in a
565 # string. It defines three groups: `source` is the source code
566 # (including leading indentation and prompts); `indent` is the
567 # indentation of the first (PS1) line of the source code; and
568 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000569 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000570 # Source consists of a PS1 line followed by zero or more PS2 lines.
571 (?P<source>
572 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
573 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
574 \n?
575 # Want consists of any non-blank lines that do not start with PS1.
576 (?P<want> (?:(?![ ]*$) # Not a blank line
577 (?![ ]*>>>) # Not a line starting with PS1
578 .*$\n? # But any other line
579 )*)
580 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000581
Edward Lopera6b68322004-08-26 00:05:43 +0000582 # A regular expression for handling `want` strings that contain
583 # expected exceptions. It divides `want` into three pieces:
584 # - the traceback header line (`hdr`)
585 # - the traceback stack (`stack`)
586 # - the exception message (`msg`), as generated by
587 # traceback.format_exception_only()
588 # `msg` may have multiple lines. We assume/require that the
589 # exception message is the first non-indented line starting with a word
590 # character following the traceback header line.
591 _EXCEPTION_RE = re.compile(r"""
592 # Grab the traceback header. Different versions of Python have
593 # said different things on the first traceback line.
594 ^(?P<hdr> Traceback\ \(
595 (?: most\ recent\ call\ last
596 | innermost\ last
597 ) \) :
598 )
599 \s* $ # toss trailing whitespace on the header.
600 (?P<stack> .*?) # don't blink: absorb stuff until...
601 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
602 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
603
Tim Peters7ea48dd2004-08-13 01:52:59 +0000604 # A callable returning a true value iff its argument is a blank line
605 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000606 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000607
Edward Lopera1ef6112004-08-09 16:14:41 +0000608 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000609 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000610 Extract all doctest examples from the given string, and
611 collect them into a `DocTest` object.
612
613 `globs`, `name`, `filename`, and `lineno` are attributes for
614 the new `DocTest` object. See the documentation for `DocTest`
615 for more information.
616 """
617 return DocTest(self.get_examples(string, name), globs,
618 name, filename, lineno, string)
619
620 def get_examples(self, string, name='<string>'):
621 """
622 Extract all doctest examples from the given string, and return
623 them as a list of `Example` objects. Line numbers are
624 0-based, because it's most common in doctests that nothing
625 interesting appears on the same line as opening triple-quote,
626 and so the first interesting line is called \"line 1\" then.
627
628 The optional argument `name` is a name identifying this
629 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000630
631 >>> text = '''
632 ... >>> x, y = 2, 3 # no output expected
633 ... >>> if 1:
634 ... ... print x
635 ... ... print y
636 ... 2
637 ... 3
638 ...
639 ... Some text.
640 ... >>> x+y
641 ... 5
642 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000643 >>> for x in DocTestParser().get_examples(text):
Edward Loper78b58f32004-08-09 02:56:02 +0000644 ... print (x.source, x.want, x.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000645 ('x, y = 2, 3 # no output expected\\n', '', 1)
Edward Loper7c748462004-08-09 02:06:06 +0000646 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
Tim Petersbb431472004-08-09 03:51:46 +0000647 ('x+y\\n', '5\\n', 9)
Edward Loper7c748462004-08-09 02:06:06 +0000648 """
649 examples = []
650 charno, lineno = 0, 0
651 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000652 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000653 # Update lineno (lines before this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000654 lineno += string.count('\n', charno, m.start())
Edward Loper7c748462004-08-09 02:06:06 +0000655 # Extract source/want from the regexp match.
Edward Lopera6b68322004-08-26 00:05:43 +0000656 (source, want, exc_msg) = self._parse_example(m, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000657 # Extract extra options from the source.
658 options = self._find_options(source, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000659 # Create an Example, and add it to the list.
Edward Loperb51b2342004-08-17 16:37:12 +0000660 if not self._IS_BLANK_OR_COMMENT(source):
Edward Lopera6b68322004-08-26 00:05:43 +0000661 examples.append( Example(source, want, exc_msg,
662 lineno=lineno,
663 indent=len(m.group('indent')),
664 options=options) )
Edward Loper7c748462004-08-09 02:06:06 +0000665 # Update lineno (lines inside this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000666 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000667 # Update charno.
668 charno = m.end()
669 return examples
670
Edward Lopera1ef6112004-08-09 16:14:41 +0000671 def get_program(self, string, name="<string>"):
Edward Loper7c748462004-08-09 02:06:06 +0000672 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000673 Return an executable program from the given string, as a string.
Edward Loper7c748462004-08-09 02:06:06 +0000674
675 The format of this isn't rigidly defined. In general, doctest
676 examples become the executable statements in the result, and
677 their expected outputs become comments, preceded by an \"#Expected:\"
678 comment. Everything else (text, comments, everything not part of
679 a doctest test) is also placed in comments.
680
Edward Lopera1ef6112004-08-09 16:14:41 +0000681 The optional argument `name` is a name identifying this
682 string, and is only used for error messages.
683
Edward Loper7c748462004-08-09 02:06:06 +0000684 >>> text = '''
685 ... >>> x, y = 2, 3 # no output expected
686 ... >>> if 1:
687 ... ... print x
688 ... ... print y
689 ... 2
690 ... 3
691 ...
692 ... Some text.
693 ... >>> x+y
694 ... 5
695 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000696 >>> print DocTestParser().get_program(text)
Edward Loper7c748462004-08-09 02:06:06 +0000697 x, y = 2, 3 # no output expected
698 if 1:
699 print x
700 print y
701 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000702 ## 2
703 ## 3
Edward Loper7c748462004-08-09 02:06:06 +0000704 #
Edward Lopera5db6002004-08-12 02:41:30 +0000705 # Some text.
Edward Loper7c748462004-08-09 02:06:06 +0000706 x+y
707 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000708 ## 5
Edward Loper7c748462004-08-09 02:06:06 +0000709 """
Edward Lopera5db6002004-08-12 02:41:30 +0000710 string = string.expandtabs()
711 # If all lines begin with the same indentation, then strip it.
712 min_indent = self._min_indent(string)
713 if min_indent > 0:
714 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
715
Edward Loper7c748462004-08-09 02:06:06 +0000716 output = []
717 charnum, lineno = 0, 0
718 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000719 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000720 # Add any text before this example, as a comment.
721 if m.start() > charnum:
Edward Lopera1ef6112004-08-09 16:14:41 +0000722 lines = string[charnum:m.start()-1].split('\n')
Edward Loper7c748462004-08-09 02:06:06 +0000723 output.extend([self._comment_line(l) for l in lines])
724 lineno += len(lines)
725
726 # Extract source/want from the regexp match.
Edward Lopera6b68322004-08-26 00:05:43 +0000727 (source, want, exc_msg) = self._parse_example(m, name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000728 # Display the source
729 output.append(source)
730 # Display the expected output, if any
731 if want:
732 output.append('# Expected:')
Edward Lopera5db6002004-08-12 02:41:30 +0000733 output.extend(['## '+l for l in want.split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000734
735 # Update the line number & char number.
Edward Lopera1ef6112004-08-09 16:14:41 +0000736 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000737 charnum = m.end()
738 # Add any remaining text, as comments.
739 output.extend([self._comment_line(l)
Edward Lopera1ef6112004-08-09 16:14:41 +0000740 for l in string[charnum:].split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000741 # Trim junk on both ends.
742 while output and output[-1] == '#':
743 output.pop()
744 while output and output[0] == '#':
745 output.pop(0)
746 # Combine the output, and return it.
747 return '\n'.join(output)
748
Edward Loper74bca7a2004-08-12 02:27:44 +0000749 def _parse_example(self, m, name, lineno):
750 """
751 Given a regular expression match from `_EXAMPLE_RE` (`m`),
752 return a pair `(source, want)`, where `source` is the matched
753 example's source code (with prompts and indentation stripped);
754 and `want` is the example's expected output (with indentation
755 stripped).
756
757 `name` is the string's name, and `lineno` is the line number
758 where the example starts; both are used for error messages.
759 """
Edward Loper7c748462004-08-09 02:06:06 +0000760 # Get the example's indentation level.
761 indent = len(m.group('indent'))
762
763 # Divide source into lines; check that they're properly
764 # indented; and then strip their indentation & prompts.
765 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000766 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000767 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000768 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000769
Tim Petersc5049152004-08-22 17:34:58 +0000770 # Divide want into lines; check that it's properly indented; and
771 # then strip the indentation. Spaces before the last newline should
772 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000773 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000774 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000775 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
776 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000777 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000778 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000779 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000780
Edward Lopera6b68322004-08-26 00:05:43 +0000781 # If `want` contains a traceback message, then extract it.
782 m = self._EXCEPTION_RE.match(want)
783 if m:
784 exc_msg = m.group('msg')
785 else:
786 exc_msg = None
787
788 return source, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000789
Edward Loper74bca7a2004-08-12 02:27:44 +0000790 # This regular expression looks for option directives in the
791 # source code of an example. Option directives are comments
792 # starting with "doctest:". Warning: this may give false
793 # positives for string-literals that contain the string
794 # "#doctest:". Eliminating these false positives would require
795 # actually parsing the string; but we limit them by ignoring any
796 # line containing "#doctest:" that is *followed* by a quote mark.
797 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
798 re.MULTILINE)
799
800 def _find_options(self, source, name, lineno):
801 """
802 Return a dictionary containing option overrides extracted from
803 option directives in the given source string.
804
805 `name` is the string's name, and `lineno` is the line number
806 where the example starts; both are used for error messages.
807 """
808 options = {}
809 # (note: with the current regexp, this will match at most once:)
810 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
811 option_strings = m.group(1).replace(',', ' ').split()
812 for option in option_strings:
813 if (option[0] not in '+-' or
814 option[1:] not in OPTIONFLAGS_BY_NAME):
815 raise ValueError('line %r of the doctest for %s '
816 'has an invalid option: %r' %
817 (lineno+1, name, option))
818 flag = OPTIONFLAGS_BY_NAME[option[1:]]
819 options[flag] = (option[0] == '+')
820 if options and self._IS_BLANK_OR_COMMENT(source):
821 raise ValueError('line %r of the doctest for %s has an option '
822 'directive on a line with no example: %r' %
823 (lineno, name, source))
824 return options
825
Edward Lopera5db6002004-08-12 02:41:30 +0000826 # This regular expression finds the indentation of every non-blank
827 # line in a string.
828 _INDENT_RE = re.compile('^([ ]+)(?=\S)', re.MULTILINE)
829
830 def _min_indent(self, s):
831 "Return the minimum indentation of any non-blank line in `s`"
832 return min([len(indent) for indent in self._INDENT_RE.findall(s)])
833
Edward Loper7c748462004-08-09 02:06:06 +0000834 def _comment_line(self, line):
Edward Loper74bca7a2004-08-12 02:27:44 +0000835 "Return a commented form of the given line"
Edward Loper7c748462004-08-09 02:06:06 +0000836 line = line.rstrip()
Tim Petersdd0e4752004-08-09 03:31:56 +0000837 if line:
Edward Lopera5db6002004-08-12 02:41:30 +0000838 return '# '+line
Tim Petersdd0e4752004-08-09 03:31:56 +0000839 else:
840 return '#'
Edward Loper7c748462004-08-09 02:06:06 +0000841
Edward Lopera1ef6112004-08-09 16:14:41 +0000842 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000843 """
844 Given the lines of a source string (including prompts and
845 leading indentation), check to make sure that every prompt is
846 followed by a space character. If any line is not followed by
847 a space character, then raise ValueError.
848 """
Edward Loper7c748462004-08-09 02:06:06 +0000849 for i, line in enumerate(lines):
850 if len(line) >= indent+4 and line[indent+3] != ' ':
851 raise ValueError('line %r of the docstring for %s '
852 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000853 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000854 line[indent:indent+3], line))
855
Edward Lopera1ef6112004-08-09 16:14:41 +0000856 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000857 """
858 Check that every line in the given list starts with the given
859 prefix; if any line does not, then raise a ValueError.
860 """
Edward Loper7c748462004-08-09 02:06:06 +0000861 for i, line in enumerate(lines):
862 if line and not line.startswith(prefix):
863 raise ValueError('line %r of the docstring for %s has '
864 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000865 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000866
867
868######################################################################
869## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000870######################################################################
871
872class DocTestFinder:
873 """
874 A class used to extract the DocTests that are relevant to a given
875 object, from its docstring and the docstrings of its contained
876 objects. Doctests can currently be extracted from the following
877 object types: modules, functions, classes, methods, staticmethods,
878 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000879 """
880
Edward Lopera1ef6112004-08-09 16:14:41 +0000881 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000882 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000883 """
884 Create a new doctest finder.
885
Edward Lopera1ef6112004-08-09 16:14:41 +0000886 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000887 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000888 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000889 signature for this factory function should match the signature
890 of the DocTest constructor.
891
Tim Peters8485b562004-08-04 18:46:34 +0000892 If the optional argument `recurse` is false, then `find` will
893 only examine the given object, and not any contained objects.
894 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000895 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000896 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000897 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000898 # _namefilter is undocumented, and exists only for temporary backward-
899 # compatibility support of testmod's deprecated isprivate mess.
900 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000901
902 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000903 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000904 """
905 Return a list of the DocTests that are defined by the given
906 object's docstring, or by any of its contained objects'
907 docstrings.
908
909 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000910 the given object. If the module is not specified or is None, then
911 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000912 correct module. The object's module is used:
913
914 - As a default namespace, if `globs` is not specified.
915 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000916 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000917 - To find the name of the file containing the object.
918 - To help find the line number of the object within its
919 file.
920
Tim Petersf3f57472004-08-08 06:11:48 +0000921 Contained objects whose module does not match `module` are ignored.
922
923 If `module` is False, no attempt to find the module will be made.
924 This is obscure, of use mostly in tests: if `module` is False, or
925 is None but cannot be found automatically, then all objects are
926 considered to belong to the (non-existent) module, so all contained
927 objects will (recursively) be searched for doctests.
928
Tim Peters8485b562004-08-04 18:46:34 +0000929 The globals for each DocTest is formed by combining `globs`
930 and `extraglobs` (bindings in `extraglobs` override bindings
931 in `globs`). A new copy of the globals dictionary is created
932 for each DocTest. If `globs` is not specified, then it
933 defaults to the module's `__dict__`, if specified, or {}
934 otherwise. If `extraglobs` is not specified, then it defaults
935 to {}.
936
Tim Peters8485b562004-08-04 18:46:34 +0000937 """
938 # If name was not specified, then extract it from the object.
939 if name is None:
940 name = getattr(obj, '__name__', None)
941 if name is None:
942 raise ValueError("DocTestFinder.find: name must be given "
943 "when obj.__name__ doesn't exist: %r" %
944 (type(obj),))
945
946 # Find the module that contains the given object (if obj is
947 # a module, then module=obj.). Note: this may fail, in which
948 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000949 if module is False:
950 module = None
951 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000952 module = inspect.getmodule(obj)
953
954 # Read the module's source code. This is used by
955 # DocTestFinder._find_lineno to find the line number for a
956 # given object's docstring.
957 try:
958 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
959 source_lines = linecache.getlines(file)
960 if not source_lines:
961 source_lines = None
962 except TypeError:
963 source_lines = None
964
965 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000966 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000967 if module is None:
968 globs = {}
969 else:
970 globs = module.__dict__.copy()
971 else:
972 globs = globs.copy()
973 if extraglobs is not None:
974 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000975
Tim Peters8485b562004-08-04 18:46:34 +0000976 # Recursively expore `obj`, extracting DocTests.
977 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000978 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000979 return tests
980
981 def _filter(self, obj, prefix, base):
982 """
983 Return true if the given object should not be examined.
984 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000985 return (self._namefilter is not None and
986 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000987
988 def _from_module(self, module, object):
989 """
990 Return true if the given object is defined in the given
991 module.
992 """
993 if module is None:
994 return True
995 elif inspect.isfunction(object):
996 return module.__dict__ is object.func_globals
997 elif inspect.isclass(object):
998 return module.__name__ == object.__module__
999 elif inspect.getmodule(object) is not None:
1000 return module is inspect.getmodule(object)
1001 elif hasattr(object, '__module__'):
1002 return module.__name__ == object.__module__
1003 elif isinstance(object, property):
1004 return True # [XX] no way not be sure.
1005 else:
1006 raise ValueError("object must be a class or function")
1007
Tim Petersf3f57472004-08-08 06:11:48 +00001008 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +00001009 """
1010 Find tests for the given object and any contained objects, and
1011 add them to `tests`.
1012 """
1013 if self._verbose:
1014 print 'Finding tests in %s' % name
1015
1016 # If we've already processed this object, then ignore it.
1017 if id(obj) in seen:
1018 return
1019 seen[id(obj)] = 1
1020
1021 # Find a test for this object, and add it to the list of tests.
1022 test = self._get_test(obj, name, module, globs, source_lines)
1023 if test is not None:
1024 tests.append(test)
1025
1026 # Look for tests in a module's contained objects.
1027 if inspect.ismodule(obj) and self._recurse:
1028 for valname, val in obj.__dict__.items():
1029 # Check if this contained object should be ignored.
1030 if self._filter(val, name, valname):
1031 continue
1032 valname = '%s.%s' % (name, valname)
1033 # Recurse to functions & classes.
1034 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +00001035 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001036 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001037 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001038
1039 # Look for tests in a module's __test__ dictionary.
1040 if inspect.ismodule(obj) and self._recurse:
1041 for valname, val in getattr(obj, '__test__', {}).items():
1042 if not isinstance(valname, basestring):
1043 raise ValueError("DocTestFinder.find: __test__ keys "
1044 "must be strings: %r" %
1045 (type(valname),))
1046 if not (inspect.isfunction(val) or inspect.isclass(val) or
1047 inspect.ismethod(val) or inspect.ismodule(val) or
1048 isinstance(val, basestring)):
1049 raise ValueError("DocTestFinder.find: __test__ values "
1050 "must be strings, functions, methods, "
1051 "classes, or modules: %r" %
1052 (type(val),))
1053 valname = '%s.%s' % (name, valname)
1054 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001055 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001056
1057 # Look for tests in a class's contained objects.
1058 if inspect.isclass(obj) and self._recurse:
1059 for valname, val in obj.__dict__.items():
1060 # Check if this contained object should be ignored.
1061 if self._filter(val, name, valname):
1062 continue
1063 # Special handling for staticmethod/classmethod.
1064 if isinstance(val, staticmethod):
1065 val = getattr(obj, valname)
1066 if isinstance(val, classmethod):
1067 val = getattr(obj, valname).im_func
1068
1069 # Recurse to methods, properties, and nested classes.
1070 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001071 isinstance(val, property)) and
1072 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001073 valname = '%s.%s' % (name, valname)
1074 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001075 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001076
1077 def _get_test(self, obj, name, module, globs, source_lines):
1078 """
1079 Return a DocTest for the given object, if it defines a docstring;
1080 otherwise, return None.
1081 """
1082 # Extract the object's docstring. If it doesn't have one,
1083 # then return None (no test for this object).
1084 if isinstance(obj, basestring):
1085 docstring = obj
1086 else:
1087 try:
1088 if obj.__doc__ is None:
1089 return None
1090 docstring = str(obj.__doc__)
1091 except (TypeError, AttributeError):
1092 return None
1093
1094 # Don't bother if the docstring is empty.
1095 if not docstring:
1096 return None
1097
1098 # Find the docstring's location in the file.
1099 lineno = self._find_lineno(obj, source_lines)
1100
1101 # Return a DocTest for this object.
1102 if module is None:
1103 filename = None
1104 else:
1105 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001106 if filename[-4:] in (".pyc", ".pyo"):
1107 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001108 return self._parser.get_doctest(docstring, globs, name,
1109 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001110
1111 def _find_lineno(self, obj, source_lines):
1112 """
1113 Return a line number of the given object's docstring. Note:
1114 this method assumes that the object has a docstring.
1115 """
1116 lineno = None
1117
1118 # Find the line number for modules.
1119 if inspect.ismodule(obj):
1120 lineno = 0
1121
1122 # Find the line number for classes.
1123 # Note: this could be fooled if a class is defined multiple
1124 # times in a single file.
1125 if inspect.isclass(obj):
1126 if source_lines is None:
1127 return None
1128 pat = re.compile(r'^\s*class\s*%s\b' %
1129 getattr(obj, '__name__', '-'))
1130 for i, line in enumerate(source_lines):
1131 if pat.match(line):
1132 lineno = i
1133 break
1134
1135 # Find the line number for functions & methods.
1136 if inspect.ismethod(obj): obj = obj.im_func
1137 if inspect.isfunction(obj): obj = obj.func_code
1138 if inspect.istraceback(obj): obj = obj.tb_frame
1139 if inspect.isframe(obj): obj = obj.f_code
1140 if inspect.iscode(obj):
1141 lineno = getattr(obj, 'co_firstlineno', None)-1
1142
1143 # Find the line number where the docstring starts. Assume
1144 # that it's the first line that begins with a quote mark.
1145 # Note: this could be fooled by a multiline function
1146 # signature, where a continuation line begins with a quote
1147 # mark.
1148 if lineno is not None:
1149 if source_lines is None:
1150 return lineno+1
1151 pat = re.compile('(^|.*:)\s*\w*("|\')')
1152 for lineno in range(lineno, len(source_lines)):
1153 if pat.match(source_lines[lineno]):
1154 return lineno
1155
1156 # We couldn't find the line number.
1157 return None
1158
1159######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001160## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001161######################################################################
1162
Tim Peters8485b562004-08-04 18:46:34 +00001163class DocTestRunner:
1164 """
1165 A class used to run DocTest test cases, and accumulate statistics.
1166 The `run` method is used to process a single DocTest case. It
1167 returns a tuple `(f, t)`, where `t` is the number of test cases
1168 tried, and `f` is the number of test cases that failed.
1169
1170 >>> tests = DocTestFinder().find(_TestClass)
1171 >>> runner = DocTestRunner(verbose=False)
1172 >>> for test in tests:
1173 ... print runner.run(test)
1174 (0, 2)
1175 (0, 1)
1176 (0, 2)
1177 (0, 2)
1178
1179 The `summarize` method prints a summary of all the test cases that
1180 have been run by the runner, and returns an aggregated `(f, t)`
1181 tuple:
1182
1183 >>> runner.summarize(verbose=1)
1184 4 items passed all tests:
1185 2 tests in _TestClass
1186 2 tests in _TestClass.__init__
1187 2 tests in _TestClass.get
1188 1 tests in _TestClass.square
1189 7 tests in 4 items.
1190 7 passed and 0 failed.
1191 Test passed.
1192 (0, 7)
1193
1194 The aggregated number of tried examples and failed examples is
1195 also available via the `tries` and `failures` attributes:
1196
1197 >>> runner.tries
1198 7
1199 >>> runner.failures
1200 0
1201
1202 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001203 by an `OutputChecker`. This comparison may be customized with a
1204 number of option flags; see the documentation for `testmod` for
1205 more information. If the option flags are insufficient, then the
1206 comparison may also be customized by passing a subclass of
1207 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001208
1209 The test runner's display output can be controlled in two ways.
1210 First, an output function (`out) can be passed to
1211 `TestRunner.run`; this function will be called with strings that
1212 should be displayed. It defaults to `sys.stdout.write`. If
1213 capturing the output is not sufficient, then the display output
1214 can be also customized by subclassing DocTestRunner, and
1215 overriding the methods `report_start`, `report_success`,
1216 `report_unexpected_exception`, and `report_failure`.
1217 """
1218 # This divider string is used to separate failure messages, and to
1219 # separate sections of the summary.
1220 DIVIDER = "*" * 70
1221
Edward Loper34fcb142004-08-09 02:45:41 +00001222 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001223 """
1224 Create a new test runner.
1225
Edward Loper34fcb142004-08-09 02:45:41 +00001226 Optional keyword arg `checker` is the `OutputChecker` that
1227 should be used to compare the expected outputs and actual
1228 outputs of doctest examples.
1229
Tim Peters8485b562004-08-04 18:46:34 +00001230 Optional keyword arg 'verbose' prints lots of stuff if true,
1231 only failures if false; by default, it's true iff '-v' is in
1232 sys.argv.
1233
1234 Optional argument `optionflags` can be used to control how the
1235 test runner compares expected output to actual output, and how
1236 it displays failures. See the documentation for `testmod` for
1237 more information.
1238 """
Edward Loper34fcb142004-08-09 02:45:41 +00001239 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001240 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001241 verbose = '-v' in sys.argv
1242 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001243 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001244 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001245
Tim Peters8485b562004-08-04 18:46:34 +00001246 # Keep track of the examples we've run.
1247 self.tries = 0
1248 self.failures = 0
1249 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001250
Tim Peters8485b562004-08-04 18:46:34 +00001251 # Create a fake output target for capturing doctest output.
1252 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001253
Tim Peters8485b562004-08-04 18:46:34 +00001254 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001255 # Reporting methods
1256 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001257
Tim Peters8485b562004-08-04 18:46:34 +00001258 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001259 """
Tim Peters8485b562004-08-04 18:46:34 +00001260 Report that the test runner is about to process the given
1261 example. (Only displays a message if verbose=True)
1262 """
1263 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001264 if example.want:
1265 out('Trying:\n' + _indent(example.source) +
1266 'Expecting:\n' + _indent(example.want))
1267 else:
1268 out('Trying:\n' + _indent(example.source) +
1269 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001270
Tim Peters8485b562004-08-04 18:46:34 +00001271 def report_success(self, out, test, example, got):
1272 """
1273 Report that the given example ran successfully. (Only
1274 displays a message if verbose=True)
1275 """
1276 if self._verbose:
1277 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001278
Tim Peters8485b562004-08-04 18:46:34 +00001279 def report_failure(self, out, test, example, got):
1280 """
1281 Report that the given example failed.
1282 """
1283 # Print an error message.
Edward Loper8e4a34b2004-08-12 02:34:27 +00001284 out(self._failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001285 self._checker.output_difference(example.want, got,
1286 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001287
Tim Peters8485b562004-08-04 18:46:34 +00001288 def report_unexpected_exception(self, out, test, example, exc_info):
1289 """
1290 Report that the given example raised an unexpected exception.
1291 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001292 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001293 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001294
Edward Loper8e4a34b2004-08-12 02:34:27 +00001295 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001296 out = [self.DIVIDER]
1297 if test.filename:
1298 if test.lineno is not None and example.lineno is not None:
1299 lineno = test.lineno + example.lineno + 1
1300 else:
1301 lineno = '?'
1302 out.append('File "%s", line %s, in %s' %
1303 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001304 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001305 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1306 out.append('Failed example:')
1307 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001308 out.append(_indent(source))
1309 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001310
Tim Peters8485b562004-08-04 18:46:34 +00001311 #/////////////////////////////////////////////////////////////////
1312 # DocTest Running
1313 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001314
Tim Peters8485b562004-08-04 18:46:34 +00001315 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001316 """
Tim Peters8485b562004-08-04 18:46:34 +00001317 Run the examples in `test`. Write the outcome of each example
1318 with one of the `DocTestRunner.report_*` methods, using the
1319 writer function `out`. `compileflags` is the set of compiler
1320 flags that should be used to execute examples. Return a tuple
1321 `(f, t)`, where `t` is the number of examples tried, and `f`
1322 is the number of examples that failed. The examples are run
1323 in the namespace `test.globs`.
1324 """
1325 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001326 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001327
1328 # Save the option flags (since option directives can be used
1329 # to modify them).
1330 original_optionflags = self.optionflags
1331
1332 # Process each example.
1333 for example in test.examples:
Edward Loper74bca7a2004-08-12 02:27:44 +00001334 # Merge in the example's options.
1335 self.optionflags = original_optionflags
1336 if example.options:
1337 for (optionflag, val) in example.options.items():
1338 if val:
1339 self.optionflags |= optionflag
1340 else:
1341 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001342
1343 # Record that we started this example.
1344 tries += 1
1345 self.report_start(out, test, example)
1346
1347 # Run the example in the given context (globs), and record
1348 # any exception that gets raised. (But don't intercept
1349 # keyboard interrupts.)
1350 try:
Tim Peters208ca702004-08-09 04:12:36 +00001351 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001352 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001353 compileflags, 1) in test.globs
1354 exception = None
1355 except KeyboardInterrupt:
1356 raise
1357 except:
1358 exception = sys.exc_info()
1359
Tim Peters208ca702004-08-09 04:12:36 +00001360 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001361 self._fakeout.truncate(0)
1362
1363 # If the example executed without raising any exceptions,
1364 # then verify its output and report its outcome.
1365 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001366 if self._checker.check_output(example.want, got,
1367 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001368 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001369 else:
Tim Peters8485b562004-08-04 18:46:34 +00001370 self.report_failure(out, test, example, got)
1371 failures += 1
1372
1373 # If the example raised an exception, then check if it was
1374 # expected.
1375 else:
1376 exc_info = sys.exc_info()
1377 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1378
Edward Lopera6b68322004-08-26 00:05:43 +00001379 # If `example.exc_msg` is None, then we weren't
1380 # expecting an exception.
1381 if example.exc_msg is None:
Tim Peters8485b562004-08-04 18:46:34 +00001382 self.report_unexpected_exception(out, test, example,
1383 exc_info)
1384 failures += 1
Edward Lopera6b68322004-08-26 00:05:43 +00001385 # If `example.exc_msg` matches the actual exception
1386 # message (`exc_msg`), then the example succeeds.
1387 elif (self._checker.check_output(example.exc_msg, exc_msg,
1388 self.optionflags)):
1389 self.report_success(out, test, example,
1390 got + _exception_traceback(exc_info))
1391 # Otherwise, the example fails.
Tim Peters8485b562004-08-04 18:46:34 +00001392 else:
Edward Lopera6b68322004-08-26 00:05:43 +00001393 self.report_failure(out, test, example,
1394 got + _exception_traceback(exc_info))
1395 failures += 1
Tim Peters8485b562004-08-04 18:46:34 +00001396
1397 # Restore the option flags (in case they were modified)
1398 self.optionflags = original_optionflags
1399
1400 # Record and return the number of failures and tries.
1401 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001402 return failures, tries
1403
Tim Peters8485b562004-08-04 18:46:34 +00001404 def __record_outcome(self, test, f, t):
1405 """
1406 Record the fact that the given DocTest (`test`) generated `f`
1407 failures out of `t` tried examples.
1408 """
1409 f2, t2 = self._name2ft.get(test.name, (0,0))
1410 self._name2ft[test.name] = (f+f2, t+t2)
1411 self.failures += f
1412 self.tries += t
1413
1414 def run(self, test, compileflags=None, out=None, clear_globs=True):
1415 """
1416 Run the examples in `test`, and display the results using the
1417 writer function `out`.
1418
1419 The examples are run in the namespace `test.globs`. If
1420 `clear_globs` is true (the default), then this namespace will
1421 be cleared after the test runs, to help with garbage
1422 collection. If you would like to examine the namespace after
1423 the test completes, then use `clear_globs=False`.
1424
1425 `compileflags` gives the set of flags that should be used by
1426 the Python compiler when running the examples. If not
1427 specified, then it will default to the set of future-import
1428 flags that apply to `globs`.
1429
1430 The output of each example is checked using
1431 `DocTestRunner.check_output`, and the results are formatted by
1432 the `DocTestRunner.report_*` methods.
1433 """
1434 if compileflags is None:
1435 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001436
Tim Peters6c542b72004-08-09 16:43:36 +00001437 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001438 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001439 out = save_stdout.write
1440 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001441
Tim Peters6c542b72004-08-09 16:43:36 +00001442 # Patch pdb.set_trace to restore sys.stdout, so that interactive
1443 # debugging output is visible (not still redirected to self._fakeout).
1444 # Note that we run "the real" pdb.set_trace (captured at doctest
1445 # import time) in our replacement. Because the current run() may
1446 # run another doctest (and so on), the current pdb.set_trace may be
1447 # our set_trace function, which changes sys.stdout. If we called
1448 # a chain of those, we wouldn't be left with the save_stdout
1449 # *this* run() invocation wants.
Jim Fulton356fd192004-08-09 11:34:47 +00001450 def set_trace():
Tim Peters6c542b72004-08-09 16:43:36 +00001451 sys.stdout = save_stdout
Jim Fulton356fd192004-08-09 11:34:47 +00001452 real_pdb_set_trace()
1453
Tim Peters6c542b72004-08-09 16:43:36 +00001454 save_set_trace = pdb.set_trace
1455 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001456 try:
Tim Peters8485b562004-08-04 18:46:34 +00001457 return self.__run(test, compileflags, out)
1458 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001459 sys.stdout = save_stdout
1460 pdb.set_trace = save_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001461 if clear_globs:
1462 test.globs.clear()
1463
1464 #/////////////////////////////////////////////////////////////////
1465 # Summarization
1466 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001467 def summarize(self, verbose=None):
1468 """
Tim Peters8485b562004-08-04 18:46:34 +00001469 Print a summary of all the test cases that have been run by
1470 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1471 the total number of failed examples, and `t` is the total
1472 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001473
Tim Peters8485b562004-08-04 18:46:34 +00001474 The optional `verbose` argument controls how detailed the
1475 summary is. If the verbosity is not specified, then the
1476 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001477 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001478 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001479 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001480 notests = []
1481 passed = []
1482 failed = []
1483 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001484 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001485 name, (f, t) = x
1486 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001487 totalt += t
1488 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001489 if t == 0:
1490 notests.append(name)
1491 elif f == 0:
1492 passed.append( (name, t) )
1493 else:
1494 failed.append(x)
1495 if verbose:
1496 if notests:
1497 print len(notests), "items had no tests:"
1498 notests.sort()
1499 for thing in notests:
1500 print " ", thing
1501 if passed:
1502 print len(passed), "items passed all tests:"
1503 passed.sort()
1504 for thing, count in passed:
1505 print " %3d tests in %s" % (count, thing)
1506 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001507 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001508 print len(failed), "items had failures:"
1509 failed.sort()
1510 for thing, (f, t) in failed:
1511 print " %3d of %3d in %s" % (f, t, thing)
1512 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001513 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001514 print totalt - totalf, "passed and", totalf, "failed."
1515 if totalf:
1516 print "***Test Failed***", totalf, "failures."
1517 elif verbose:
1518 print "Test passed."
1519 return totalf, totalt
1520
Edward Loper34fcb142004-08-09 02:45:41 +00001521class OutputChecker:
1522 """
1523 A class used to check the whether the actual output from a doctest
1524 example matches the expected output. `OutputChecker` defines two
1525 methods: `check_output`, which compares a given pair of outputs,
1526 and returns true if they match; and `output_difference`, which
1527 returns a string describing the differences between two outputs.
1528 """
1529 def check_output(self, want, got, optionflags):
1530 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001531 Return True iff the actual output from an example (`got`)
1532 matches the expected output (`want`). These strings are
1533 always considered to match if they are identical; but
1534 depending on what option flags the test runner is using,
1535 several non-exact match types are also possible. See the
1536 documentation for `TestRunner` for more information about
1537 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001538 """
1539 # Handle the common case first, for efficiency:
1540 # if they're string-identical, always return true.
1541 if got == want:
1542 return True
1543
1544 # The values True and False replaced 1 and 0 as the return
1545 # value for boolean comparisons in Python 2.3.
1546 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1547 if (got,want) == ("True\n", "1\n"):
1548 return True
1549 if (got,want) == ("False\n", "0\n"):
1550 return True
1551
1552 # <BLANKLINE> can be used as a special sequence to signify a
1553 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1554 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1555 # Replace <BLANKLINE> in want with a blank line.
1556 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1557 '', want)
1558 # If a line in got contains only spaces, then remove the
1559 # spaces.
1560 got = re.sub('(?m)^\s*?$', '', got)
1561 if got == want:
1562 return True
1563
1564 # This flag causes doctest to ignore any differences in the
1565 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001566 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001567 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001568 got = ' '.join(got.split())
1569 want = ' '.join(want.split())
1570 if got == want:
1571 return True
1572
1573 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001574 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001575 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001576 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001577 return True
1578
1579 # We didn't find any match; return false.
1580 return False
1581
Tim Petersc6cbab02004-08-22 19:43:28 +00001582 # Should we do a fancy diff?
1583 def _do_a_fancy_diff(self, want, got, optionflags):
1584 # Not unless they asked for a fancy diff.
1585 if not optionflags & (UNIFIED_DIFF |
1586 CONTEXT_DIFF |
1587 NDIFF_DIFF):
1588 return False
1589 # If expected output uses ellipsis, a meaningful fancy diff is
1590 # too hard.
1591 if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1592 return False
1593 # ndiff does intraline difference marking, so can be useful even
1594 # for 1-line inputs.
1595 if optionflags & NDIFF_DIFF:
1596 return True
1597 # The other diff types need at least a few lines to be helpful.
1598 return want.count('\n') > 2 and got.count('\n') > 2
1599
Edward Loper34fcb142004-08-09 02:45:41 +00001600 def output_difference(self, want, got, optionflags):
1601 """
1602 Return a string describing the differences between the
Edward Loper74bca7a2004-08-12 02:27:44 +00001603 expected output for an example (`want`) and the actual output
1604 (`got`). `optionflags` is the set of option flags used to
Edward Loperaacf0832004-08-26 01:19:50 +00001605 compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001606 """
Edward Loper68ba9a62004-08-12 02:43:49 +00001607 # If <BLANKLINE>s are being used, then replace blank lines
1608 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001609 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001610 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001611
1612 # Check if we should use diff. Don't use diff if the actual
1613 # or expected outputs are too short, or if the expected output
1614 # contains an ellipsis marker.
Tim Petersc6cbab02004-08-22 19:43:28 +00001615 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001616 # Split want & got into lines.
1617 want_lines = [l+'\n' for l in want.split('\n')]
1618 got_lines = [l+'\n' for l in got.split('\n')]
1619 # Use difflib to find their differences.
1620 if optionflags & UNIFIED_DIFF:
1621 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1622 fromfile='Expected', tofile='Got')
Tim Petersc6cbab02004-08-22 19:43:28 +00001623 kind = 'unified diff'
Edward Loper34fcb142004-08-09 02:45:41 +00001624 elif optionflags & CONTEXT_DIFF:
1625 diff = difflib.context_diff(want_lines, got_lines, n=2,
1626 fromfile='Expected', tofile='Got')
Tim Petersc6cbab02004-08-22 19:43:28 +00001627 kind = 'context diff'
1628 elif optionflags & NDIFF_DIFF:
1629 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1630 diff = list(engine.compare(want_lines, got_lines))
1631 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001632 else:
1633 assert 0, 'Bad diff option'
1634 # Remove trailing whitespace on diff output.
1635 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001636 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001637
1638 # If we're not using diff, then simply list the expected
1639 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001640 if want and got:
1641 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1642 elif want:
1643 return 'Expected:\n%sGot nothing\n' % _indent(want)
1644 elif got:
1645 return 'Expected nothing\nGot:\n%s' % _indent(got)
1646 else:
1647 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001648
Tim Peters19397e52004-08-06 22:02:59 +00001649class DocTestFailure(Exception):
1650 """A DocTest example has failed in debugging mode.
1651
1652 The exception instance has variables:
1653
1654 - test: the DocTest object being run
1655
1656 - excample: the Example object that failed
1657
1658 - got: the actual output
1659 """
1660 def __init__(self, test, example, got):
1661 self.test = test
1662 self.example = example
1663 self.got = got
1664
1665 def __str__(self):
1666 return str(self.test)
1667
1668class UnexpectedException(Exception):
1669 """A DocTest example has encountered an unexpected exception
1670
1671 The exception instance has variables:
1672
1673 - test: the DocTest object being run
1674
1675 - excample: the Example object that failed
1676
1677 - exc_info: the exception info
1678 """
1679 def __init__(self, test, example, exc_info):
1680 self.test = test
1681 self.example = example
1682 self.exc_info = exc_info
1683
1684 def __str__(self):
1685 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001686
Tim Peters19397e52004-08-06 22:02:59 +00001687class DebugRunner(DocTestRunner):
1688 r"""Run doc tests but raise an exception as soon as there is a failure.
1689
1690 If an unexpected exception occurs, an UnexpectedException is raised.
1691 It contains the test, the example, and the original exception:
1692
1693 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001694 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1695 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001696 >>> try:
1697 ... runner.run(test)
1698 ... except UnexpectedException, failure:
1699 ... pass
1700
1701 >>> failure.test is test
1702 True
1703
1704 >>> failure.example.want
1705 '42\n'
1706
1707 >>> exc_info = failure.exc_info
1708 >>> raise exc_info[0], exc_info[1], exc_info[2]
1709 Traceback (most recent call last):
1710 ...
1711 KeyError
1712
1713 We wrap the original exception to give the calling application
1714 access to the test and example information.
1715
1716 If the output doesn't match, then a DocTestFailure is raised:
1717
Edward Lopera1ef6112004-08-09 16:14:41 +00001718 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001719 ... >>> x = 1
1720 ... >>> x
1721 ... 2
1722 ... ''', {}, 'foo', 'foo.py', 0)
1723
1724 >>> try:
1725 ... runner.run(test)
1726 ... except DocTestFailure, failure:
1727 ... pass
1728
1729 DocTestFailure objects provide access to the test:
1730
1731 >>> failure.test is test
1732 True
1733
1734 As well as to the example:
1735
1736 >>> failure.example.want
1737 '2\n'
1738
1739 and the actual output:
1740
1741 >>> failure.got
1742 '1\n'
1743
1744 If a failure or error occurs, the globals are left intact:
1745
1746 >>> del test.globs['__builtins__']
1747 >>> test.globs
1748 {'x': 1}
1749
Edward Lopera1ef6112004-08-09 16:14:41 +00001750 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001751 ... >>> x = 2
1752 ... >>> raise KeyError
1753 ... ''', {}, 'foo', 'foo.py', 0)
1754
1755 >>> runner.run(test)
1756 Traceback (most recent call last):
1757 ...
1758 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001759
Tim Peters19397e52004-08-06 22:02:59 +00001760 >>> del test.globs['__builtins__']
1761 >>> test.globs
1762 {'x': 2}
1763
1764 But the globals are cleared if there is no error:
1765
Edward Lopera1ef6112004-08-09 16:14:41 +00001766 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001767 ... >>> x = 2
1768 ... ''', {}, 'foo', 'foo.py', 0)
1769
1770 >>> runner.run(test)
1771 (0, 1)
1772
1773 >>> test.globs
1774 {}
1775
1776 """
1777
1778 def run(self, test, compileflags=None, out=None, clear_globs=True):
1779 r = DocTestRunner.run(self, test, compileflags, out, False)
1780 if clear_globs:
1781 test.globs.clear()
1782 return r
1783
1784 def report_unexpected_exception(self, out, test, example, exc_info):
1785 raise UnexpectedException(test, example, exc_info)
1786
1787 def report_failure(self, out, test, example, got):
1788 raise DocTestFailure(test, example, got)
1789
Tim Peters8485b562004-08-04 18:46:34 +00001790######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001791## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001792######################################################################
1793# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001794
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001795def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001796 report=True, optionflags=0, extraglobs=None,
1797 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001798 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001799 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001800
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001801 Test examples in docstrings in functions and classes reachable
1802 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001803 with m.__doc__. Unless isprivate is specified, private names
1804 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001805
1806 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001807 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001808 function and class docstrings are tested even if the name is private;
1809 strings are tested directly, as if they were docstrings.
1810
1811 Return (#failures, #tests).
1812
1813 See doctest.__doc__ for an overview.
1814
1815 Optional keyword arg "name" gives the name of the module; by default
1816 use m.__name__.
1817
1818 Optional keyword arg "globs" gives a dict to be used as the globals
1819 when executing examples; by default, use m.__dict__. A copy of this
1820 dict is actually used for each docstring, so that each docstring's
1821 examples start with a clean slate.
1822
Tim Peters8485b562004-08-04 18:46:34 +00001823 Optional keyword arg "extraglobs" gives a dictionary that should be
1824 merged into the globals that are used to execute examples. By
1825 default, no extra globals are used. This is new in 2.4.
1826
Tim Peters8a7d2d52001-01-16 07:10:57 +00001827 Optional keyword arg "verbose" prints lots of stuff if true, prints
1828 only failures if false; by default, it's true iff "-v" is in sys.argv.
1829
Tim Peters8a7d2d52001-01-16 07:10:57 +00001830 Optional keyword arg "report" prints a summary at the end when true,
1831 else prints nothing at the end. In verbose mode, the summary is
1832 detailed, else very brief (in fact, empty if all tests passed).
1833
Tim Peters6ebe61f2003-06-27 20:48:05 +00001834 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001835 and defaults to 0. This is new in 2.3. Possible values (see the
1836 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001837
1838 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001839 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001840 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001841 ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001842 UNIFIED_DIFF
Tim Peters8485b562004-08-04 18:46:34 +00001843 CONTEXT_DIFF
Tim Petersf82a9de2004-08-22 20:51:53 +00001844 NDIFF_DIFF
Tim Peters19397e52004-08-06 22:02:59 +00001845
1846 Optional keyword arg "raise_on_error" raises an exception on the
1847 first unexpected exception or failure. This allows failures to be
1848 post-mortem debugged.
1849
Tim Petersf727c6c2004-08-08 01:48:59 +00001850 Deprecated in Python 2.4:
1851 Optional keyword arg "isprivate" specifies a function used to
1852 determine whether a name is private. The default function is
1853 treat all functions as public. Optionally, "isprivate" can be
1854 set to doctest.is_private to skip over functions marked as private
1855 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001856 """
1857
1858 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001859 Advanced tomfoolery: testmod runs methods of a local instance of
1860 class doctest.Tester, then merges the results into (or creates)
1861 global Tester instance doctest.master. Methods of doctest.master
1862 can be called directly too, if you want to do something unusual.
1863 Passing report=0 to testmod is especially useful then, to delay
1864 displaying a summary. Invoke doctest.master.summarize(verbose)
1865 when you're done fiddling.
1866 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001867 if isprivate is not None:
1868 warnings.warn("the isprivate argument is deprecated; "
1869 "examine DocTestFinder.find() lists instead",
1870 DeprecationWarning)
1871
Tim Peters8485b562004-08-04 18:46:34 +00001872 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001873 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001874 # DWA - m will still be None if this wasn't invoked from the command
1875 # line, in which case the following TypeError is about as good an error
1876 # as we should expect
1877 m = sys.modules.get('__main__')
1878
Tim Peters8485b562004-08-04 18:46:34 +00001879 # Check that we were actually given a module.
1880 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001881 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001882
1883 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001884 if name is None:
1885 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001886
1887 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001888 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001889
1890 if raise_on_error:
1891 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1892 else:
1893 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1894
Tim Peters8485b562004-08-04 18:46:34 +00001895 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1896 runner.run(test)
1897
Tim Peters8a7d2d52001-01-16 07:10:57 +00001898 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001899 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001900
Tim Peters8485b562004-08-04 18:46:34 +00001901 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001902
Tim Peters8485b562004-08-04 18:46:34 +00001903def run_docstring_examples(f, globs, verbose=False, name="NoName",
1904 compileflags=None, optionflags=0):
1905 """
1906 Test examples in the given object's docstring (`f`), using `globs`
1907 as globals. Optional argument `name` is used in failure messages.
1908 If the optional argument `verbose` is true, then generate output
1909 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001910
Tim Peters8485b562004-08-04 18:46:34 +00001911 `compileflags` gives the set of flags that should be used by the
1912 Python compiler when running the examples. If not specified, then
1913 it will default to the set of future-import flags that apply to
1914 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001915
Tim Peters8485b562004-08-04 18:46:34 +00001916 Optional keyword arg `optionflags` specifies options for the
1917 testing and output. See the documentation for `testmod` for more
1918 information.
1919 """
1920 # Find, parse, and run all tests in the given module.
1921 finder = DocTestFinder(verbose=verbose, recurse=False)
1922 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1923 for test in finder.find(f, name, globs=globs):
1924 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001925
Tim Peters8485b562004-08-04 18:46:34 +00001926######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001927## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001928######################################################################
1929# This is provided only for backwards compatibility. It's not
1930# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001931
Tim Peters8485b562004-08-04 18:46:34 +00001932class Tester:
1933 def __init__(self, mod=None, globs=None, verbose=None,
1934 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001935
1936 warnings.warn("class Tester is deprecated; "
1937 "use class doctest.DocTestRunner instead",
1938 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001939 if mod is None and globs is None:
1940 raise TypeError("Tester.__init__: must specify mod or globs")
1941 if mod is not None and not _ismodule(mod):
1942 raise TypeError("Tester.__init__: mod must be a module; %r" %
1943 (mod,))
1944 if globs is None:
1945 globs = mod.__dict__
1946 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001947
Tim Peters8485b562004-08-04 18:46:34 +00001948 self.verbose = verbose
1949 self.isprivate = isprivate
1950 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001951 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001952 self.testrunner = DocTestRunner(verbose=verbose,
1953 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001954
Tim Peters8485b562004-08-04 18:46:34 +00001955 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001956 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001957 if self.verbose:
1958 print "Running string", name
1959 (f,t) = self.testrunner.run(test)
1960 if self.verbose:
1961 print f, "of", t, "examples failed in string", name
1962 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001963
Tim Petersf3f57472004-08-08 06:11:48 +00001964 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001965 f = t = 0
1966 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001967 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001968 for test in tests:
1969 (f2, t2) = self.testrunner.run(test)
1970 (f,t) = (f+f2, t+t2)
1971 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001972
Tim Peters8485b562004-08-04 18:46:34 +00001973 def rundict(self, d, name, module=None):
1974 import new
1975 m = new.module(name)
1976 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001977 if module is None:
1978 module = False
1979 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001980
Tim Peters8485b562004-08-04 18:46:34 +00001981 def run__test__(self, d, name):
1982 import new
1983 m = new.module(name)
1984 m.__test__ = d
1985 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001986
Tim Peters8485b562004-08-04 18:46:34 +00001987 def summarize(self, verbose=None):
1988 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001989
Tim Peters8485b562004-08-04 18:46:34 +00001990 def merge(self, other):
1991 d = self.testrunner._name2ft
1992 for name, (f, t) in other.testrunner._name2ft.items():
1993 if name in d:
1994 print "*** Tester.merge: '" + name + "' in both" \
1995 " testers; summing outcomes."
1996 f2, t2 = d[name]
1997 f = f + f2
1998 t = t + t2
1999 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00002000
Tim Peters8485b562004-08-04 18:46:34 +00002001######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002002## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002003######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002004
Tim Peters19397e52004-08-06 22:02:59 +00002005class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002006
Edward Loper34fcb142004-08-09 02:45:41 +00002007 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2008 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002009
Jim Fultona643b652004-07-14 19:06:50 +00002010 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002011 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002012 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002013 self._dt_test = test
2014 self._dt_setUp = setUp
2015 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002016
Jim Fultona643b652004-07-14 19:06:50 +00002017 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00002018 if self._dt_setUp is not None:
2019 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00002020
2021 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00002022 if self._dt_tearDown is not None:
2023 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002024
2025 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002026 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002027 old = sys.stdout
2028 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00002029 runner = DocTestRunner(optionflags=self._dt_optionflags,
2030 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002031
Jim Fultona643b652004-07-14 19:06:50 +00002032 try:
Tim Peters19397e52004-08-06 22:02:59 +00002033 runner.DIVIDER = "-"*70
2034 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00002035 finally:
2036 sys.stdout = old
2037
2038 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002039 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002040
Tim Peters19397e52004-08-06 22:02:59 +00002041 def format_failure(self, err):
2042 test = self._dt_test
2043 if test.lineno is None:
2044 lineno = 'unknown line number'
2045 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002046 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002047 lname = '.'.join(test.name.split('.')[-1:])
2048 return ('Failed doctest test for %s\n'
2049 ' File "%s", line %s, in %s\n\n%s'
2050 % (test.name, test.filename, lineno, lname, err)
2051 )
2052
2053 def debug(self):
2054 r"""Run the test case without results and without catching exceptions
2055
2056 The unit test framework includes a debug method on test cases
2057 and test suites to support post-mortem debugging. The test code
2058 is run in such a way that errors are not caught. This way a
2059 caller can catch the errors and initiate post-mortem debugging.
2060
2061 The DocTestCase provides a debug method that raises
2062 UnexpectedException errors if there is an unexepcted
2063 exception:
2064
Edward Lopera1ef6112004-08-09 16:14:41 +00002065 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002066 ... {}, 'foo', 'foo.py', 0)
2067 >>> case = DocTestCase(test)
2068 >>> try:
2069 ... case.debug()
2070 ... except UnexpectedException, failure:
2071 ... pass
2072
2073 The UnexpectedException contains the test, the example, and
2074 the original exception:
2075
2076 >>> failure.test is test
2077 True
2078
2079 >>> failure.example.want
2080 '42\n'
2081
2082 >>> exc_info = failure.exc_info
2083 >>> raise exc_info[0], exc_info[1], exc_info[2]
2084 Traceback (most recent call last):
2085 ...
2086 KeyError
2087
2088 If the output doesn't match, then a DocTestFailure is raised:
2089
Edward Lopera1ef6112004-08-09 16:14:41 +00002090 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002091 ... >>> x = 1
2092 ... >>> x
2093 ... 2
2094 ... ''', {}, 'foo', 'foo.py', 0)
2095 >>> case = DocTestCase(test)
2096
2097 >>> try:
2098 ... case.debug()
2099 ... except DocTestFailure, failure:
2100 ... pass
2101
2102 DocTestFailure objects provide access to the test:
2103
2104 >>> failure.test is test
2105 True
2106
2107 As well as to the example:
2108
2109 >>> failure.example.want
2110 '2\n'
2111
2112 and the actual output:
2113
2114 >>> failure.got
2115 '1\n'
2116
2117 """
2118
Edward Loper34fcb142004-08-09 02:45:41 +00002119 runner = DebugRunner(optionflags=self._dt_optionflags,
2120 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002121 runner.run(self._dt_test)
Jim Fultona643b652004-07-14 19:06:50 +00002122
2123 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002124 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002125
2126 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002127 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002128 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2129
2130 __str__ = __repr__
2131
2132 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002133 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002134
Tim Peters19397e52004-08-06 22:02:59 +00002135def DocTestSuite(module=None, globs=None, extraglobs=None,
2136 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002137 setUp=lambda: None, tearDown=lambda: None,
2138 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002139 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002140 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002141
Tim Peters19397e52004-08-06 22:02:59 +00002142 This converts each documentation string in a module that
2143 contains doctest tests to a unittest test case. If any of the
2144 tests in a doc string fail, then the test case fails. An exception
2145 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002146 (sometimes approximate) line number.
2147
Tim Peters19397e52004-08-06 22:02:59 +00002148 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002149 can be either a module or a module name.
2150
2151 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002152 """
Jim Fultona643b652004-07-14 19:06:50 +00002153
Tim Peters8485b562004-08-04 18:46:34 +00002154 if test_finder is None:
2155 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002156
Tim Peters19397e52004-08-06 22:02:59 +00002157 module = _normalize_module(module)
2158 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2159 if globs is None:
2160 globs = module.__dict__
2161 if not tests: # [XX] why do we want to do this?
2162 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002163
2164 tests.sort()
2165 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002166 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002167 if len(test.examples) == 0:
2168 continue
Tim Peters8485b562004-08-04 18:46:34 +00002169 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002170 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002171 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002172 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002173 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002174 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2175 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002176
2177 return suite
2178
2179class DocFileCase(DocTestCase):
2180
2181 def id(self):
2182 return '_'.join(self._dt_test.name.split('.'))
2183
2184 def __repr__(self):
2185 return self._dt_test.filename
2186 __str__ = __repr__
2187
2188 def format_failure(self, err):
2189 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2190 % (self._dt_test.name, self._dt_test.filename, err)
2191 )
2192
2193def DocFileTest(path, package=None, globs=None,
2194 setUp=None, tearDown=None,
2195 optionflags=0):
2196 package = _normalize_module(package)
2197 name = path.split('/')[-1]
2198 dir = os.path.split(package.__file__)[0]
2199 path = os.path.join(dir, *(path.split('/')))
2200 doc = open(path).read()
2201
2202 if globs is None:
2203 globs = {}
2204
Edward Lopera1ef6112004-08-09 16:14:41 +00002205 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002206
2207 return DocFileCase(test, optionflags, setUp, tearDown)
2208
2209def DocFileSuite(*paths, **kw):
2210 """Creates a suite of doctest files.
2211
2212 One or more text file paths are given as strings. These should
2213 use "/" characters to separate path segments. Paths are relative
2214 to the directory of the calling module, or relative to the package
2215 passed as a keyword argument.
2216
2217 A number of options may be provided as keyword arguments:
2218
2219 package
2220 The name of a Python package. Text-file paths will be
2221 interpreted relative to the directory containing this package.
2222 The package may be supplied as a package object or as a dotted
2223 package name.
2224
2225 setUp
2226 The name of a set-up function. This is called before running the
2227 tests in each file.
2228
2229 tearDown
2230 The name of a tear-down function. This is called after running the
2231 tests in each file.
2232
2233 globs
2234 A dictionary containing initial global variables for the tests.
2235 """
2236 suite = unittest.TestSuite()
2237
2238 # We do this here so that _normalize_module is called at the right
2239 # level. If it were called in DocFileTest, then this function
2240 # would be the caller and we might guess the package incorrectly.
2241 kw['package'] = _normalize_module(kw.get('package'))
2242
2243 for path in paths:
2244 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002245
Tim Petersdb3756d2003-06-29 05:30:48 +00002246 return suite
2247
Tim Peters8485b562004-08-04 18:46:34 +00002248######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002249## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002250######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002251
Tim Peters19397e52004-08-06 22:02:59 +00002252def script_from_examples(s):
2253 r"""Extract script from text with examples.
2254
2255 Converts text with examples to a Python script. Example input is
2256 converted to regular code. Example output and all other words
2257 are converted to comments:
2258
2259 >>> text = '''
2260 ... Here are examples of simple math.
2261 ...
2262 ... Python has super accurate integer addition
2263 ...
2264 ... >>> 2 + 2
2265 ... 5
2266 ...
2267 ... And very friendly error messages:
2268 ...
2269 ... >>> 1/0
2270 ... To Infinity
2271 ... And
2272 ... Beyond
2273 ...
2274 ... You can use logic if you want:
2275 ...
2276 ... >>> if 0:
2277 ... ... blah
2278 ... ... blah
2279 ... ...
2280 ...
2281 ... Ho hum
2282 ... '''
2283
2284 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002285 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002286 #
Edward Lopera5db6002004-08-12 02:41:30 +00002287 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002288 #
2289 2 + 2
2290 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002291 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002292 #
Edward Lopera5db6002004-08-12 02:41:30 +00002293 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002294 #
2295 1/0
2296 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002297 ## To Infinity
2298 ## And
2299 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002300 #
Edward Lopera5db6002004-08-12 02:41:30 +00002301 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002302 #
2303 if 0:
2304 blah
2305 blah
2306 <BLANKLINE>
2307 #
Edward Lopera5db6002004-08-12 02:41:30 +00002308 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002309 """
2310
Edward Lopera1ef6112004-08-09 16:14:41 +00002311 return DocTestParser().get_program(s)
Tim Peters19397e52004-08-06 22:02:59 +00002312
Tim Peters8485b562004-08-04 18:46:34 +00002313def _want_comment(example):
2314 """
Tim Peters19397e52004-08-06 22:02:59 +00002315 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002316 """
Jim Fultona643b652004-07-14 19:06:50 +00002317 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002318 want = example.want
2319 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002320 if want[-1] == '\n':
2321 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002322 want = "\n# ".join(want.split("\n"))
2323 want = "\n# Expected:\n# %s" % want
2324 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002325
2326def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002327 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002328
2329 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002330 test to be debugged and the name (within the module) of the object
2331 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002332 """
Tim Peters8485b562004-08-04 18:46:34 +00002333 module = _normalize_module(module)
2334 tests = DocTestFinder().find(module)
2335 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002336 if not test:
2337 raise ValueError(name, "not found in tests")
2338 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002339 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002340 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002341
Jim Fultona643b652004-07-14 19:06:50 +00002342def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002343 """Debug a single doctest docstring, in argument `src`'"""
2344 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002345 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002346
Jim Fultona643b652004-07-14 19:06:50 +00002347def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002348 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002349 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002350
Tim Petersb6a04d62004-08-23 21:37:56 +00002351 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2352 # docs say, a file so created cannot be opened by name a second time
2353 # on modern Windows boxes, and execfile() needs to open it.
2354 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002355 f = open(srcfilename, 'w')
2356 f.write(src)
2357 f.close()
2358
Tim Petersb6a04d62004-08-23 21:37:56 +00002359 try:
2360 if globs:
2361 globs = globs.copy()
2362 else:
2363 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002364
Tim Petersb6a04d62004-08-23 21:37:56 +00002365 if pm:
2366 try:
2367 execfile(srcfilename, globs, globs)
2368 except:
2369 print sys.exc_info()[1]
2370 pdb.post_mortem(sys.exc_info()[2])
2371 else:
2372 # Note that %r is vital here. '%s' instead can, e.g., cause
2373 # backslashes to get treated as metacharacters on Windows.
2374 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2375
2376 finally:
2377 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002378
Jim Fultona643b652004-07-14 19:06:50 +00002379def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002380 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002381
2382 Provide the module (or dotted name of the module) containing the
2383 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002384 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002385 """
Tim Peters8485b562004-08-04 18:46:34 +00002386 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002387 testsrc = testsource(module, name)
2388 debug_script(testsrc, pm, module.__dict__)
2389
Tim Peters8485b562004-08-04 18:46:34 +00002390######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002391## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002392######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002393class _TestClass:
2394 """
2395 A pointless class, for sanity-checking of docstring testing.
2396
2397 Methods:
2398 square()
2399 get()
2400
2401 >>> _TestClass(13).get() + _TestClass(-12).get()
2402 1
2403 >>> hex(_TestClass(13).square().get())
2404 '0xa9'
2405 """
2406
2407 def __init__(self, val):
2408 """val -> _TestClass object with associated value val.
2409
2410 >>> t = _TestClass(123)
2411 >>> print t.get()
2412 123
2413 """
2414
2415 self.val = val
2416
2417 def square(self):
2418 """square() -> square TestClass's associated value
2419
2420 >>> _TestClass(13).square().get()
2421 169
2422 """
2423
2424 self.val = self.val ** 2
2425 return self
2426
2427 def get(self):
2428 """get() -> return TestClass's associated value.
2429
2430 >>> x = _TestClass(-42)
2431 >>> print x.get()
2432 -42
2433 """
2434
2435 return self.val
2436
2437__test__ = {"_TestClass": _TestClass,
2438 "string": r"""
2439 Example of a string object, searched as-is.
2440 >>> x = 1; y = 2
2441 >>> x + y, x * y
2442 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002443 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002444
Tim Peters6ebe61f2003-06-27 20:48:05 +00002445 "bool-int equivalence": r"""
2446 In 2.2, boolean expressions displayed
2447 0 or 1. By default, we still accept
2448 them. This can be disabled by passing
2449 DONT_ACCEPT_TRUE_FOR_1 to the new
2450 optionflags argument.
2451 >>> 4 == 4
2452 1
2453 >>> 4 == 4
2454 True
2455 >>> 4 > 4
2456 0
2457 >>> 4 > 4
2458 False
2459 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002460
Tim Peters8485b562004-08-04 18:46:34 +00002461 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002462 Blank lines can be marked with <BLANKLINE>:
2463 >>> print 'foo\n\nbar\n'
2464 foo
2465 <BLANKLINE>
2466 bar
2467 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002468 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002469
2470 "ellipsis": r"""
2471 If the ellipsis flag is used, then '...' can be used to
2472 elide substrings in the desired output:
2473 >>> print range(1000) #doctest: +ELLIPSIS
2474 [0, 1, 2, ..., 999]
2475 """,
2476
2477 "whitespace normalization": r"""
2478 If the whitespace normalization flag is used, then
2479 differences in whitespace are ignored.
2480 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2481 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2482 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2483 27, 28, 29]
2484 """,
2485 }
Tim Peters8485b562004-08-04 18:46:34 +00002486
Tim Peters8a7d2d52001-01-16 07:10:57 +00002487def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002488 r = unittest.TextTestRunner()
2489 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002490
2491if __name__ == "__main__":
2492 _test()