blob: aa523a64d6e1671634dcb45af387a9c85ae31924 [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__ = [
Tim Peters8485b562004-08-04 18:46:34 +0000173 'is_private',
174 'Example',
175 'DocTest',
176 'DocTestFinder',
177 'DocTestRunner',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000178 'testmod',
179 'run_docstring_examples',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000180 'Tester',
Tim Peters19397e52004-08-06 22:02:59 +0000181 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000182 'DocTestSuite',
183 'testsource',
184 'debug',
Tim Peters8485b562004-08-04 18:46:34 +0000185# 'master',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000186]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000187
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000188import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000189
Tim Peters19397e52004-08-06 22:02:59 +0000190import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000191import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000192import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000193from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000194
Jim Fulton356fd192004-08-09 11:34:47 +0000195real_pdb_set_trace = pdb.set_trace
196
Tim Peters19397e52004-08-06 22:02:59 +0000197# There are 4 basic classes:
198# - Example: a <source, want> pair, plus an intra-docstring line number.
199# - DocTest: a collection of examples, parsed from a docstring, plus
200# info about where the docstring came from (name, filename, lineno).
201# - DocTestFinder: extracts DocTests from a given object's docstring and
202# its contained objects' docstrings.
203# - DocTestRunner: runs DocTest cases, and accumulates statistics.
204#
205# So the basic picture is:
206#
207# list of:
208# +------+ +---------+ +-------+
209# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
210# +------+ +---------+ +-------+
211# | Example |
212# | ... |
213# | Example |
214# +---------+
215
Edward Loperac20f572004-08-12 02:02:24 +0000216# Option constants.
217OPTIONFLAGS_BY_NAME = {}
218def register_optionflag(name):
219 flag = 1 << len(OPTIONFLAGS_BY_NAME)
220 OPTIONFLAGS_BY_NAME[name] = flag
221 return flag
222
223DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
224DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
225NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
226ELLIPSIS = register_optionflag('ELLIPSIS')
227UNIFIED_DIFF = register_optionflag('UNIFIED_DIFF')
228CONTEXT_DIFF = register_optionflag('CONTEXT_DIFF')
229
230# Special string markers for use in `want` strings:
231BLANKLINE_MARKER = '<BLANKLINE>'
232ELLIPSIS_MARKER = '...'
233
Tim Peters8485b562004-08-04 18:46:34 +0000234######################################################################
235## Table of Contents
236######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000237# 1. Utility Functions
238# 2. Example & DocTest -- store test cases
239# 3. DocTest Parser -- extracts examples from strings
240# 4. DocTest Finder -- extracts test cases from objects
241# 5. DocTest Runner -- runs test cases
242# 6. Test Functions -- convenient wrappers for testing
243# 7. Tester Class -- for backwards compatibility
244# 8. Unittest Support
245# 9. Debugging Support
246# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000247
Tim Peters8485b562004-08-04 18:46:34 +0000248######################################################################
249## 1. Utility Functions
250######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000251
252def is_private(prefix, base):
253 """prefix, base -> true iff name prefix + "." + base is "private".
254
255 Prefix may be an empty string, and base does not contain a period.
256 Prefix is ignored (although functions you write conforming to this
257 protocol may make use of it).
258 Return true iff base begins with an (at least one) underscore, but
259 does not both begin and end with (at least) two underscores.
260
Tim Petersbafb1fe2004-08-08 01:52:57 +0000261 >>> warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
262 ... "doctest", 0)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000263 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000264 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000265 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000266 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000267 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000268 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000269 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000270 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000271 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000272 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000273 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000274 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000275 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000276 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000277 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000278 warnings.warn("is_private is deprecated; it wasn't useful; "
279 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000280 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000281 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
282
Tim Peters8485b562004-08-04 18:46:34 +0000283def _extract_future_flags(globs):
284 """
285 Return the compiler-flags associated with the future features that
286 have been imported into the given namespace (globs).
287 """
288 flags = 0
289 for fname in __future__.all_feature_names:
290 feature = globs.get(fname, None)
291 if feature is getattr(__future__, fname):
292 flags |= feature.compiler_flag
293 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000294
Tim Peters8485b562004-08-04 18:46:34 +0000295def _normalize_module(module, depth=2):
296 """
297 Return the module specified by `module`. In particular:
298 - If `module` is a module, then return module.
299 - If `module` is a string, then import and return the
300 module with that name.
301 - If `module` is None, then return the calling module.
302 The calling module is assumed to be the module of
303 the stack frame at the given depth in the call stack.
304 """
305 if inspect.ismodule(module):
306 return module
307 elif isinstance(module, (str, unicode)):
308 return __import__(module, globals(), locals(), ["*"])
309 elif module is None:
310 return sys.modules[sys._getframe(depth).f_globals['__name__']]
311 else:
312 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000313
Edward Lopera1ef6112004-08-09 16:14:41 +0000314def _tag_msg(tag, msg, indent=' '):
Tim Peters8485b562004-08-04 18:46:34 +0000315 """
316 Return a string that displays a tag-and-message pair nicely,
317 keeping the tag and its message on the same line when that
Edward Lopera1ef6112004-08-09 16:14:41 +0000318 makes sense. If the message is displayed on separate lines,
319 then `indent` is added to the beginning of each line.
Tim Peters8485b562004-08-04 18:46:34 +0000320 """
Tim Peters8485b562004-08-04 18:46:34 +0000321 # If the message doesn't end in a newline, then add one.
322 if msg[-1:] != '\n':
323 msg += '\n'
324 # If the message is short enough, and contains no internal
325 # newlines, then display it on the same line as the tag.
326 # Otherwise, display the tag on its own line.
327 if (len(tag) + len(msg) < 75 and
328 msg.find('\n', 0, len(msg)-1) == -1):
329 return '%s: %s' % (tag, msg)
330 else:
Edward Lopera1ef6112004-08-09 16:14:41 +0000331 msg = '\n'.join([indent+l for l in msg[:-1].split('\n')])
332 return '%s:\n%s\n' % (tag, msg)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000333
Edward Loper8e4a34b2004-08-12 02:34:27 +0000334def _exception_traceback(exc_info):
335 """
336 Return a string containing a traceback message for the given
337 exc_info tuple (as returned by sys.exc_info()).
338 """
339 # Get a traceback message.
340 excout = StringIO()
341 exc_type, exc_val, exc_tb = exc_info
342 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
343 return excout.getvalue()
344
Tim Peters8485b562004-08-04 18:46:34 +0000345# Override some StringIO methods.
346class _SpoofOut(StringIO):
347 def getvalue(self):
348 result = StringIO.getvalue(self)
349 # If anything at all was written, make sure there's a trailing
350 # newline. There's no way for the expected output to indicate
351 # that a trailing newline is missing.
352 if result and not result.endswith("\n"):
353 result += "\n"
354 # Prevent softspace from screwing up the next test case, in
355 # case they used print with a trailing comma in an example.
356 if hasattr(self, "softspace"):
357 del self.softspace
358 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000359
Tim Peters8485b562004-08-04 18:46:34 +0000360 def truncate(self, size=None):
361 StringIO.truncate(self, size)
362 if hasattr(self, "softspace"):
363 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000364
Tim Peters8485b562004-08-04 18:46:34 +0000365######################################################################
366## 2. Example & DocTest
367######################################################################
368## - An "example" is a <source, want> pair, where "source" is a
369## fragment of source code, and "want" is the expected output for
370## "source." The Example class also includes information about
371## where the example was extracted from.
372##
Edward Lopera1ef6112004-08-09 16:14:41 +0000373## - A "doctest" is a collection of examples, typically extracted from
374## a string (such as an object's docstring). The DocTest class also
375## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000376
Tim Peters8485b562004-08-04 18:46:34 +0000377class Example:
378 """
379 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000380 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000381
Edward Loper74bca7a2004-08-12 02:27:44 +0000382 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000383 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000384
Edward Loper74bca7a2004-08-12 02:27:44 +0000385 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000386 from stdout, or a traceback in case of exception). `want` ends
387 with a newline unless it's empty, in which case it's an empty
388 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000389
Edward Loper74bca7a2004-08-12 02:27:44 +0000390 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000391 this Example where the Example begins. This line number is
392 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000393
394 - indent: The example's indentation in the DocTest string.
395 I.e., the number of space characters that preceed the
396 example's first prompt.
397
398 - options: A dictionary mapping from option flags to True or
399 False, which is used to override default options for this
400 example. Any option flags not contained in this dictionary
401 are left at their default value (as specified by the
402 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000403 """
Edward Loper74bca7a2004-08-12 02:27:44 +0000404 def __init__(self, source, want, lineno, indent=0, options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000405 # Normalize inputs.
406 if not source.endswith('\n'):
407 source += '\n'
408 if want and not want.endswith('\n'):
409 want += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000410 # Store properties.
411 self.source = source
412 self.want = want
413 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000414 self.indent = indent
415 if options is None: options = {}
416 self.options = options
Tim Peters8a7d2d52001-01-16 07:10:57 +0000417
Tim Peters8485b562004-08-04 18:46:34 +0000418class DocTest:
419 """
420 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000421 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000422
Tim Peters8485b562004-08-04 18:46:34 +0000423 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000424
Tim Peters8485b562004-08-04 18:46:34 +0000425 - globs: The namespace (aka globals) that the examples should
426 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000427
Tim Peters8485b562004-08-04 18:46:34 +0000428 - name: A name identifying the DocTest (typically, the name of
429 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000430
Tim Peters8485b562004-08-04 18:46:34 +0000431 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000432 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000433
Tim Peters8485b562004-08-04 18:46:34 +0000434 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000435 begins, or `None` if the line number is unavailable. This
436 line number is zero-based, with respect to the beginning of
437 the file.
438
439 - docstring: The string that the examples were extracted from,
440 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000441 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000442 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000443 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000444 Create a new DocTest containing the given examples. The
445 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000446 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000447 assert not isinstance(examples, basestring), \
448 "DocTest no longer accepts str; use DocTestParser instead"
449 self.examples = examples
450 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000451 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000452 self.name = name
453 self.filename = filename
454 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000455
456 def __repr__(self):
457 if len(self.examples) == 0:
458 examples = 'no examples'
459 elif len(self.examples) == 1:
460 examples = '1 example'
461 else:
462 examples = '%d examples' % len(self.examples)
463 return ('<DocTest %s from %s:%s (%s)>' %
464 (self.name, self.filename, self.lineno, examples))
465
466
467 # This lets us sort tests by name:
468 def __cmp__(self, other):
469 if not isinstance(other, DocTest):
470 return -1
471 return cmp((self.name, self.filename, self.lineno, id(self)),
472 (other.name, other.filename, other.lineno, id(other)))
473
474######################################################################
Edward Lopera1ef6112004-08-09 16:14:41 +0000475## 2. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000476######################################################################
477
Edward Lopera1ef6112004-08-09 16:14:41 +0000478class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000479 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000480 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000481 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000482 # This regular expression is used to find doctest examples in a
483 # string. It defines three groups: `source` is the source code
484 # (including leading indentation and prompts); `indent` is the
485 # indentation of the first (PS1) line of the source code; and
486 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000487 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000488 # Source consists of a PS1 line followed by zero or more PS2 lines.
489 (?P<source>
490 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
491 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
492 \n?
493 # Want consists of any non-blank lines that do not start with PS1.
494 (?P<want> (?:(?![ ]*$) # Not a blank line
495 (?![ ]*>>>) # Not a line starting with PS1
496 .*$\n? # But any other line
497 )*)
498 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000499
Tim Peters7ea48dd2004-08-13 01:52:59 +0000500 # A callable returning a true value iff its argument is a blank line
501 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000502 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000503
Edward Lopera1ef6112004-08-09 16:14:41 +0000504 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000505 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000506 Extract all doctest examples from the given string, and
507 collect them into a `DocTest` object.
508
509 `globs`, `name`, `filename`, and `lineno` are attributes for
510 the new `DocTest` object. See the documentation for `DocTest`
511 for more information.
512 """
513 return DocTest(self.get_examples(string, name), globs,
514 name, filename, lineno, string)
515
516 def get_examples(self, string, name='<string>'):
517 """
518 Extract all doctest examples from the given string, and return
519 them as a list of `Example` objects. Line numbers are
520 0-based, because it's most common in doctests that nothing
521 interesting appears on the same line as opening triple-quote,
522 and so the first interesting line is called \"line 1\" then.
523
524 The optional argument `name` is a name identifying this
525 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000526
527 >>> text = '''
528 ... >>> x, y = 2, 3 # no output expected
529 ... >>> if 1:
530 ... ... print x
531 ... ... print y
532 ... 2
533 ... 3
534 ...
535 ... Some text.
536 ... >>> x+y
537 ... 5
538 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000539 >>> for x in DocTestParser().get_examples(text):
Edward Loper78b58f32004-08-09 02:56:02 +0000540 ... print (x.source, x.want, x.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000541 ('x, y = 2, 3 # no output expected\\n', '', 1)
Edward Loper7c748462004-08-09 02:06:06 +0000542 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
Tim Petersbb431472004-08-09 03:51:46 +0000543 ('x+y\\n', '5\\n', 9)
Edward Loper7c748462004-08-09 02:06:06 +0000544 """
545 examples = []
546 charno, lineno = 0, 0
547 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000548 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000549 # Update lineno (lines before this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000550 lineno += string.count('\n', charno, m.start())
Edward Loper7c748462004-08-09 02:06:06 +0000551 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000552 (source, want) = self._parse_example(m, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000553 # Extract extra options from the source.
554 options = self._find_options(source, name, lineno)
555 # If it contains no real source, then ignore it.
Tim Petersd40a92b2004-08-09 03:28:45 +0000556 if self._IS_BLANK_OR_COMMENT(source):
Edward Loper7c748462004-08-09 02:06:06 +0000557 continue
Edward Loper74bca7a2004-08-12 02:27:44 +0000558 # Create an Example, and add it to the list.
559 examples.append( Example(source, want, lineno,
560 len(m.group('indent')), options) )
Edward Loper7c748462004-08-09 02:06:06 +0000561 # Update lineno (lines inside this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000562 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000563 # Update charno.
564 charno = m.end()
565 return examples
566
Edward Lopera1ef6112004-08-09 16:14:41 +0000567 def get_program(self, string, name="<string>"):
Edward Loper7c748462004-08-09 02:06:06 +0000568 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000569 Return an executable program from the given string, as a string.
Edward Loper7c748462004-08-09 02:06:06 +0000570
571 The format of this isn't rigidly defined. In general, doctest
572 examples become the executable statements in the result, and
573 their expected outputs become comments, preceded by an \"#Expected:\"
574 comment. Everything else (text, comments, everything not part of
575 a doctest test) is also placed in comments.
576
Edward Lopera1ef6112004-08-09 16:14:41 +0000577 The optional argument `name` is a name identifying this
578 string, and is only used for error messages.
579
Edward Loper7c748462004-08-09 02:06:06 +0000580 >>> text = '''
581 ... >>> x, y = 2, 3 # no output expected
582 ... >>> if 1:
583 ... ... print x
584 ... ... print y
585 ... 2
586 ... 3
587 ...
588 ... Some text.
589 ... >>> x+y
590 ... 5
591 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000592 >>> print DocTestParser().get_program(text)
Edward Loper7c748462004-08-09 02:06:06 +0000593 x, y = 2, 3 # no output expected
594 if 1:
595 print x
596 print y
597 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000598 ## 2
599 ## 3
Edward Loper7c748462004-08-09 02:06:06 +0000600 #
Edward Lopera5db6002004-08-12 02:41:30 +0000601 # Some text.
Edward Loper7c748462004-08-09 02:06:06 +0000602 x+y
603 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000604 ## 5
Edward Loper7c748462004-08-09 02:06:06 +0000605 """
Edward Lopera5db6002004-08-12 02:41:30 +0000606 string = string.expandtabs()
607 # If all lines begin with the same indentation, then strip it.
608 min_indent = self._min_indent(string)
609 if min_indent > 0:
610 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
611
Edward Loper7c748462004-08-09 02:06:06 +0000612 output = []
613 charnum, lineno = 0, 0
614 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000615 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000616 # Add any text before this example, as a comment.
617 if m.start() > charnum:
Edward Lopera1ef6112004-08-09 16:14:41 +0000618 lines = string[charnum:m.start()-1].split('\n')
Edward Loper7c748462004-08-09 02:06:06 +0000619 output.extend([self._comment_line(l) for l in lines])
620 lineno += len(lines)
621
622 # Extract source/want from the regexp match.
Edward Loper74bca7a2004-08-12 02:27:44 +0000623 (source, want) = self._parse_example(m, name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000624 # Display the source
625 output.append(source)
626 # Display the expected output, if any
627 if want:
628 output.append('# Expected:')
Edward Lopera5db6002004-08-12 02:41:30 +0000629 output.extend(['## '+l for l in want.split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000630
631 # Update the line number & char number.
Edward Lopera1ef6112004-08-09 16:14:41 +0000632 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000633 charnum = m.end()
634 # Add any remaining text, as comments.
635 output.extend([self._comment_line(l)
Edward Lopera1ef6112004-08-09 16:14:41 +0000636 for l in string[charnum:].split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000637 # Trim junk on both ends.
638 while output and output[-1] == '#':
639 output.pop()
640 while output and output[0] == '#':
641 output.pop(0)
642 # Combine the output, and return it.
643 return '\n'.join(output)
644
Edward Loper74bca7a2004-08-12 02:27:44 +0000645 def _parse_example(self, m, name, lineno):
646 """
647 Given a regular expression match from `_EXAMPLE_RE` (`m`),
648 return a pair `(source, want)`, where `source` is the matched
649 example's source code (with prompts and indentation stripped);
650 and `want` is the example's expected output (with indentation
651 stripped).
652
653 `name` is the string's name, and `lineno` is the line number
654 where the example starts; both are used for error messages.
655 """
Edward Loper7c748462004-08-09 02:06:06 +0000656 # Get the example's indentation level.
657 indent = len(m.group('indent'))
658
659 # Divide source into lines; check that they're properly
660 # indented; and then strip their indentation & prompts.
661 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000662 self._check_prompt_blank(source_lines, indent, name, lineno)
663 self._check_prefix(source_lines[1:], ' '*indent+'.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000664 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000665
666 # Divide want into lines; check that it's properly
667 # indented; and then strip the indentation.
668 want_lines = m.group('want').rstrip().split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000669 self._check_prefix(want_lines, ' '*indent, name,
Edward Loper7c748462004-08-09 02:06:06 +0000670 lineno+len(source_lines))
671 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000672
673 return source, want
674
Edward Loper74bca7a2004-08-12 02:27:44 +0000675 # This regular expression looks for option directives in the
676 # source code of an example. Option directives are comments
677 # starting with "doctest:". Warning: this may give false
678 # positives for string-literals that contain the string
679 # "#doctest:". Eliminating these false positives would require
680 # actually parsing the string; but we limit them by ignoring any
681 # line containing "#doctest:" that is *followed* by a quote mark.
682 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
683 re.MULTILINE)
684
685 def _find_options(self, source, name, lineno):
686 """
687 Return a dictionary containing option overrides extracted from
688 option directives in the given source string.
689
690 `name` is the string's name, and `lineno` is the line number
691 where the example starts; both are used for error messages.
692 """
693 options = {}
694 # (note: with the current regexp, this will match at most once:)
695 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
696 option_strings = m.group(1).replace(',', ' ').split()
697 for option in option_strings:
698 if (option[0] not in '+-' or
699 option[1:] not in OPTIONFLAGS_BY_NAME):
700 raise ValueError('line %r of the doctest for %s '
701 'has an invalid option: %r' %
702 (lineno+1, name, option))
703 flag = OPTIONFLAGS_BY_NAME[option[1:]]
704 options[flag] = (option[0] == '+')
705 if options and self._IS_BLANK_OR_COMMENT(source):
706 raise ValueError('line %r of the doctest for %s has an option '
707 'directive on a line with no example: %r' %
708 (lineno, name, source))
709 return options
710
Edward Lopera5db6002004-08-12 02:41:30 +0000711 # This regular expression finds the indentation of every non-blank
712 # line in a string.
713 _INDENT_RE = re.compile('^([ ]+)(?=\S)', re.MULTILINE)
714
715 def _min_indent(self, s):
716 "Return the minimum indentation of any non-blank line in `s`"
717 return min([len(indent) for indent in self._INDENT_RE.findall(s)])
718
Edward Loper7c748462004-08-09 02:06:06 +0000719 def _comment_line(self, line):
Edward Loper74bca7a2004-08-12 02:27:44 +0000720 "Return a commented form of the given line"
Edward Loper7c748462004-08-09 02:06:06 +0000721 line = line.rstrip()
Tim Petersdd0e4752004-08-09 03:31:56 +0000722 if line:
Edward Lopera5db6002004-08-12 02:41:30 +0000723 return '# '+line
Tim Petersdd0e4752004-08-09 03:31:56 +0000724 else:
725 return '#'
Edward Loper7c748462004-08-09 02:06:06 +0000726
Edward Lopera1ef6112004-08-09 16:14:41 +0000727 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000728 """
729 Given the lines of a source string (including prompts and
730 leading indentation), check to make sure that every prompt is
731 followed by a space character. If any line is not followed by
732 a space character, then raise ValueError.
733 """
Edward Loper7c748462004-08-09 02:06:06 +0000734 for i, line in enumerate(lines):
735 if len(line) >= indent+4 and line[indent+3] != ' ':
736 raise ValueError('line %r of the docstring for %s '
737 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000738 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000739 line[indent:indent+3], line))
740
Edward Lopera1ef6112004-08-09 16:14:41 +0000741 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000742 """
743 Check that every line in the given list starts with the given
744 prefix; if any line does not, then raise a ValueError.
745 """
Edward Loper7c748462004-08-09 02:06:06 +0000746 for i, line in enumerate(lines):
747 if line and not line.startswith(prefix):
748 raise ValueError('line %r of the docstring for %s has '
749 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000750 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000751
752
753######################################################################
754## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000755######################################################################
756
757class DocTestFinder:
758 """
759 A class used to extract the DocTests that are relevant to a given
760 object, from its docstring and the docstrings of its contained
761 objects. Doctests can currently be extracted from the following
762 object types: modules, functions, classes, methods, staticmethods,
763 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000764 """
765
Edward Lopera1ef6112004-08-09 16:14:41 +0000766 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000767 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000768 """
769 Create a new doctest finder.
770
Edward Lopera1ef6112004-08-09 16:14:41 +0000771 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000772 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000773 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000774 signature for this factory function should match the signature
775 of the DocTest constructor.
776
Tim Peters8485b562004-08-04 18:46:34 +0000777 If the optional argument `recurse` is false, then `find` will
778 only examine the given object, and not any contained objects.
779 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000780 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000781 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000782 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000783 # _namefilter is undocumented, and exists only for temporary backward-
784 # compatibility support of testmod's deprecated isprivate mess.
785 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000786
787 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000788 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000789 """
790 Return a list of the DocTests that are defined by the given
791 object's docstring, or by any of its contained objects'
792 docstrings.
793
794 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000795 the given object. If the module is not specified or is None, then
796 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000797 correct module. The object's module is used:
798
799 - As a default namespace, if `globs` is not specified.
800 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000801 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000802 - To find the name of the file containing the object.
803 - To help find the line number of the object within its
804 file.
805
Tim Petersf3f57472004-08-08 06:11:48 +0000806 Contained objects whose module does not match `module` are ignored.
807
808 If `module` is False, no attempt to find the module will be made.
809 This is obscure, of use mostly in tests: if `module` is False, or
810 is None but cannot be found automatically, then all objects are
811 considered to belong to the (non-existent) module, so all contained
812 objects will (recursively) be searched for doctests.
813
Tim Peters8485b562004-08-04 18:46:34 +0000814 The globals for each DocTest is formed by combining `globs`
815 and `extraglobs` (bindings in `extraglobs` override bindings
816 in `globs`). A new copy of the globals dictionary is created
817 for each DocTest. If `globs` is not specified, then it
818 defaults to the module's `__dict__`, if specified, or {}
819 otherwise. If `extraglobs` is not specified, then it defaults
820 to {}.
821
Tim Peters8485b562004-08-04 18:46:34 +0000822 """
823 # If name was not specified, then extract it from the object.
824 if name is None:
825 name = getattr(obj, '__name__', None)
826 if name is None:
827 raise ValueError("DocTestFinder.find: name must be given "
828 "when obj.__name__ doesn't exist: %r" %
829 (type(obj),))
830
831 # Find the module that contains the given object (if obj is
832 # a module, then module=obj.). Note: this may fail, in which
833 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000834 if module is False:
835 module = None
836 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000837 module = inspect.getmodule(obj)
838
839 # Read the module's source code. This is used by
840 # DocTestFinder._find_lineno to find the line number for a
841 # given object's docstring.
842 try:
843 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
844 source_lines = linecache.getlines(file)
845 if not source_lines:
846 source_lines = None
847 except TypeError:
848 source_lines = None
849
850 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000851 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000852 if module is None:
853 globs = {}
854 else:
855 globs = module.__dict__.copy()
856 else:
857 globs = globs.copy()
858 if extraglobs is not None:
859 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000860
Tim Peters8485b562004-08-04 18:46:34 +0000861 # Recursively expore `obj`, extracting DocTests.
862 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000863 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000864 return tests
865
866 def _filter(self, obj, prefix, base):
867 """
868 Return true if the given object should not be examined.
869 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000870 return (self._namefilter is not None and
871 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000872
873 def _from_module(self, module, object):
874 """
875 Return true if the given object is defined in the given
876 module.
877 """
878 if module is None:
879 return True
880 elif inspect.isfunction(object):
881 return module.__dict__ is object.func_globals
882 elif inspect.isclass(object):
883 return module.__name__ == object.__module__
884 elif inspect.getmodule(object) is not None:
885 return module is inspect.getmodule(object)
886 elif hasattr(object, '__module__'):
887 return module.__name__ == object.__module__
888 elif isinstance(object, property):
889 return True # [XX] no way not be sure.
890 else:
891 raise ValueError("object must be a class or function")
892
Tim Petersf3f57472004-08-08 06:11:48 +0000893 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000894 """
895 Find tests for the given object and any contained objects, and
896 add them to `tests`.
897 """
898 if self._verbose:
899 print 'Finding tests in %s' % name
900
901 # If we've already processed this object, then ignore it.
902 if id(obj) in seen:
903 return
904 seen[id(obj)] = 1
905
906 # Find a test for this object, and add it to the list of tests.
907 test = self._get_test(obj, name, module, globs, source_lines)
908 if test is not None:
909 tests.append(test)
910
911 # Look for tests in a module's contained objects.
912 if inspect.ismodule(obj) and self._recurse:
913 for valname, val in obj.__dict__.items():
914 # Check if this contained object should be ignored.
915 if self._filter(val, name, valname):
916 continue
917 valname = '%s.%s' % (name, valname)
918 # Recurse to functions & classes.
919 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000920 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000921 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000922 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000923
924 # Look for tests in a module's __test__ dictionary.
925 if inspect.ismodule(obj) and self._recurse:
926 for valname, val in getattr(obj, '__test__', {}).items():
927 if not isinstance(valname, basestring):
928 raise ValueError("DocTestFinder.find: __test__ keys "
929 "must be strings: %r" %
930 (type(valname),))
931 if not (inspect.isfunction(val) or inspect.isclass(val) or
932 inspect.ismethod(val) or inspect.ismodule(val) or
933 isinstance(val, basestring)):
934 raise ValueError("DocTestFinder.find: __test__ values "
935 "must be strings, functions, methods, "
936 "classes, or modules: %r" %
937 (type(val),))
938 valname = '%s.%s' % (name, valname)
939 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000940 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000941
942 # Look for tests in a class's contained objects.
943 if inspect.isclass(obj) and self._recurse:
944 for valname, val in obj.__dict__.items():
945 # Check if this contained object should be ignored.
946 if self._filter(val, name, valname):
947 continue
948 # Special handling for staticmethod/classmethod.
949 if isinstance(val, staticmethod):
950 val = getattr(obj, valname)
951 if isinstance(val, classmethod):
952 val = getattr(obj, valname).im_func
953
954 # Recurse to methods, properties, and nested classes.
955 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +0000956 isinstance(val, property)) and
957 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000958 valname = '%s.%s' % (name, valname)
959 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000960 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000961
962 def _get_test(self, obj, name, module, globs, source_lines):
963 """
964 Return a DocTest for the given object, if it defines a docstring;
965 otherwise, return None.
966 """
967 # Extract the object's docstring. If it doesn't have one,
968 # then return None (no test for this object).
969 if isinstance(obj, basestring):
970 docstring = obj
971 else:
972 try:
973 if obj.__doc__ is None:
974 return None
975 docstring = str(obj.__doc__)
976 except (TypeError, AttributeError):
977 return None
978
979 # Don't bother if the docstring is empty.
980 if not docstring:
981 return None
982
983 # Find the docstring's location in the file.
984 lineno = self._find_lineno(obj, source_lines)
985
986 # Return a DocTest for this object.
987 if module is None:
988 filename = None
989 else:
990 filename = getattr(module, '__file__', module.__name__)
Edward Lopera1ef6112004-08-09 16:14:41 +0000991 return self._parser.get_doctest(docstring, globs, name,
992 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +0000993
994 def _find_lineno(self, obj, source_lines):
995 """
996 Return a line number of the given object's docstring. Note:
997 this method assumes that the object has a docstring.
998 """
999 lineno = None
1000
1001 # Find the line number for modules.
1002 if inspect.ismodule(obj):
1003 lineno = 0
1004
1005 # Find the line number for classes.
1006 # Note: this could be fooled if a class is defined multiple
1007 # times in a single file.
1008 if inspect.isclass(obj):
1009 if source_lines is None:
1010 return None
1011 pat = re.compile(r'^\s*class\s*%s\b' %
1012 getattr(obj, '__name__', '-'))
1013 for i, line in enumerate(source_lines):
1014 if pat.match(line):
1015 lineno = i
1016 break
1017
1018 # Find the line number for functions & methods.
1019 if inspect.ismethod(obj): obj = obj.im_func
1020 if inspect.isfunction(obj): obj = obj.func_code
1021 if inspect.istraceback(obj): obj = obj.tb_frame
1022 if inspect.isframe(obj): obj = obj.f_code
1023 if inspect.iscode(obj):
1024 lineno = getattr(obj, 'co_firstlineno', None)-1
1025
1026 # Find the line number where the docstring starts. Assume
1027 # that it's the first line that begins with a quote mark.
1028 # Note: this could be fooled by a multiline function
1029 # signature, where a continuation line begins with a quote
1030 # mark.
1031 if lineno is not None:
1032 if source_lines is None:
1033 return lineno+1
1034 pat = re.compile('(^|.*:)\s*\w*("|\')')
1035 for lineno in range(lineno, len(source_lines)):
1036 if pat.match(source_lines[lineno]):
1037 return lineno
1038
1039 # We couldn't find the line number.
1040 return None
1041
1042######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001043## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001044######################################################################
1045
Tim Peters8485b562004-08-04 18:46:34 +00001046class DocTestRunner:
1047 """
1048 A class used to run DocTest test cases, and accumulate statistics.
1049 The `run` method is used to process a single DocTest case. It
1050 returns a tuple `(f, t)`, where `t` is the number of test cases
1051 tried, and `f` is the number of test cases that failed.
1052
1053 >>> tests = DocTestFinder().find(_TestClass)
1054 >>> runner = DocTestRunner(verbose=False)
1055 >>> for test in tests:
1056 ... print runner.run(test)
1057 (0, 2)
1058 (0, 1)
1059 (0, 2)
1060 (0, 2)
1061
1062 The `summarize` method prints a summary of all the test cases that
1063 have been run by the runner, and returns an aggregated `(f, t)`
1064 tuple:
1065
1066 >>> runner.summarize(verbose=1)
1067 4 items passed all tests:
1068 2 tests in _TestClass
1069 2 tests in _TestClass.__init__
1070 2 tests in _TestClass.get
1071 1 tests in _TestClass.square
1072 7 tests in 4 items.
1073 7 passed and 0 failed.
1074 Test passed.
1075 (0, 7)
1076
1077 The aggregated number of tried examples and failed examples is
1078 also available via the `tries` and `failures` attributes:
1079
1080 >>> runner.tries
1081 7
1082 >>> runner.failures
1083 0
1084
1085 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001086 by an `OutputChecker`. This comparison may be customized with a
1087 number of option flags; see the documentation for `testmod` for
1088 more information. If the option flags are insufficient, then the
1089 comparison may also be customized by passing a subclass of
1090 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001091
1092 The test runner's display output can be controlled in two ways.
1093 First, an output function (`out) can be passed to
1094 `TestRunner.run`; this function will be called with strings that
1095 should be displayed. It defaults to `sys.stdout.write`. If
1096 capturing the output is not sufficient, then the display output
1097 can be also customized by subclassing DocTestRunner, and
1098 overriding the methods `report_start`, `report_success`,
1099 `report_unexpected_exception`, and `report_failure`.
1100 """
1101 # This divider string is used to separate failure messages, and to
1102 # separate sections of the summary.
1103 DIVIDER = "*" * 70
1104
Edward Loper34fcb142004-08-09 02:45:41 +00001105 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001106 """
1107 Create a new test runner.
1108
Edward Loper34fcb142004-08-09 02:45:41 +00001109 Optional keyword arg `checker` is the `OutputChecker` that
1110 should be used to compare the expected outputs and actual
1111 outputs of doctest examples.
1112
Tim Peters8485b562004-08-04 18:46:34 +00001113 Optional keyword arg 'verbose' prints lots of stuff if true,
1114 only failures if false; by default, it's true iff '-v' is in
1115 sys.argv.
1116
1117 Optional argument `optionflags` can be used to control how the
1118 test runner compares expected output to actual output, and how
1119 it displays failures. See the documentation for `testmod` for
1120 more information.
1121 """
Edward Loper34fcb142004-08-09 02:45:41 +00001122 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001123 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001124 verbose = '-v' in sys.argv
1125 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001126 self.optionflags = optionflags
1127
Tim Peters8485b562004-08-04 18:46:34 +00001128 # Keep track of the examples we've run.
1129 self.tries = 0
1130 self.failures = 0
1131 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001132
Tim Peters8485b562004-08-04 18:46:34 +00001133 # Create a fake output target for capturing doctest output.
1134 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001135
Tim Peters8485b562004-08-04 18:46:34 +00001136 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001137 # Reporting methods
1138 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001139
Tim Peters8485b562004-08-04 18:46:34 +00001140 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001141 """
Tim Peters8485b562004-08-04 18:46:34 +00001142 Report that the test runner is about to process the given
1143 example. (Only displays a message if verbose=True)
1144 """
1145 if self._verbose:
1146 out(_tag_msg("Trying", example.source) +
1147 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001148
Tim Peters8485b562004-08-04 18:46:34 +00001149 def report_success(self, out, test, example, got):
1150 """
1151 Report that the given example ran successfully. (Only
1152 displays a message if verbose=True)
1153 """
1154 if self._verbose:
1155 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001156
Tim Peters8485b562004-08-04 18:46:34 +00001157 def report_failure(self, out, test, example, got):
1158 """
1159 Report that the given example failed.
1160 """
1161 # Print an error message.
Edward Loper8e4a34b2004-08-12 02:34:27 +00001162 out(self._failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001163 self._checker.output_difference(example.want, got,
1164 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001165
Tim Peters8485b562004-08-04 18:46:34 +00001166 def report_unexpected_exception(self, out, test, example, exc_info):
1167 """
1168 Report that the given example raised an unexpected exception.
1169 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001170 out(self._failure_header(test, example) +
1171 _tag_msg("Exception raised", _exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001172
Edward Loper8e4a34b2004-08-12 02:34:27 +00001173 def _failure_header(self, test, example):
Tim Peters8485b562004-08-04 18:46:34 +00001174 s = (self.DIVIDER + "\n" +
1175 _tag_msg("Failure in example", example.source))
1176 if test.filename is None:
1177 # [XX] I'm not putting +1 here, to give the same output
1178 # as the old version. But I think it *should* go here.
1179 return s + ("from line #%s of %s\n" %
1180 (example.lineno, test.name))
1181 elif test.lineno is None:
1182 return s + ("from line #%s of %s in %s\n" %
1183 (example.lineno+1, test.name, test.filename))
1184 else:
1185 lineno = test.lineno+example.lineno+1
1186 return s + ("from line #%s of %s (%s)\n" %
1187 (lineno, test.filename, test.name))
Tim Peters7402f792001-10-02 03:53:41 +00001188
Tim Peters8485b562004-08-04 18:46:34 +00001189 #/////////////////////////////////////////////////////////////////
1190 # DocTest Running
1191 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001192
Tim Peters8485b562004-08-04 18:46:34 +00001193 # A regular expression for handling `want` strings that contain
Tim Peters41a65ea2004-08-13 03:55:05 +00001194 # expected exceptions. It divides `want` into three pieces:
1195 # - the pre-exception output (`want`)
1196 # - the traceback header line (`hdr`)
1197 # - the exception message (`msg`), as generated by
1198 # traceback.format_exception_only()
1199 # `msg` may have multiple lines. We assume/require that the
1200 # exception message is the first non-indented line starting with a word
1201 # character following the traceback header line.
1202 _EXCEPTION_RE = re.compile(r"""
1203 (?P<want> .*?) # suck up everything until traceback header
1204 # Grab the traceback header. Different versions of Python have
1205 # said different things on the first traceback line.
1206 ^(?P<hdr> Traceback\ \(
1207 (?: most\ recent\ call\ last
1208 | innermost\ last
1209 ) \) :
1210 )
1211 \s* $ # toss trailing whitespace on traceback header
1212 .*? # don't blink: absorb stuff until a line *starts* with \w
1213 ^ (?P<msg> \w+ .*)
1214 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001215
Tim Peters8485b562004-08-04 18:46:34 +00001216 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001217 """
Tim Peters8485b562004-08-04 18:46:34 +00001218 Run the examples in `test`. Write the outcome of each example
1219 with one of the `DocTestRunner.report_*` methods, using the
1220 writer function `out`. `compileflags` is the set of compiler
1221 flags that should be used to execute examples. Return a tuple
1222 `(f, t)`, where `t` is the number of examples tried, and `f`
1223 is the number of examples that failed. The examples are run
1224 in the namespace `test.globs`.
1225 """
1226 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001227 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001228
1229 # Save the option flags (since option directives can be used
1230 # to modify them).
1231 original_optionflags = self.optionflags
1232
1233 # Process each example.
1234 for example in test.examples:
Edward Loper74bca7a2004-08-12 02:27:44 +00001235 # Merge in the example's options.
1236 self.optionflags = original_optionflags
1237 if example.options:
1238 for (optionflag, val) in example.options.items():
1239 if val:
1240 self.optionflags |= optionflag
1241 else:
1242 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001243
1244 # Record that we started this example.
1245 tries += 1
1246 self.report_start(out, test, example)
1247
1248 # Run the example in the given context (globs), and record
1249 # any exception that gets raised. (But don't intercept
1250 # keyboard interrupts.)
1251 try:
Tim Peters208ca702004-08-09 04:12:36 +00001252 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001253 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001254 compileflags, 1) in test.globs
1255 exception = None
1256 except KeyboardInterrupt:
1257 raise
1258 except:
1259 exception = sys.exc_info()
1260
Tim Peters208ca702004-08-09 04:12:36 +00001261 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001262 self._fakeout.truncate(0)
1263
1264 # If the example executed without raising any exceptions,
1265 # then verify its output and report its outcome.
1266 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001267 if self._checker.check_output(example.want, got,
1268 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001269 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001270 else:
Tim Peters8485b562004-08-04 18:46:34 +00001271 self.report_failure(out, test, example, got)
1272 failures += 1
1273
1274 # If the example raised an exception, then check if it was
1275 # expected.
1276 else:
1277 exc_info = sys.exc_info()
1278 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1279
1280 # Search the `want` string for an exception. If we don't
1281 # find one, then report an unexpected exception.
1282 m = self._EXCEPTION_RE.match(example.want)
1283 if m is None:
1284 self.report_unexpected_exception(out, test, example,
1285 exc_info)
1286 failures += 1
1287 else:
Tim Peters41a65ea2004-08-13 03:55:05 +00001288 e_want, e_msg = m.group('want', 'msg')
Tim Peters8485b562004-08-04 18:46:34 +00001289 # The test passes iff the pre-exception output and
1290 # the exception description match the values given
1291 # in `want`.
Tim Peters41a65ea2004-08-13 03:55:05 +00001292 if (self._checker.check_output(e_want, got,
Edward Loper34fcb142004-08-09 02:45:41 +00001293 self.optionflags) and
Tim Peters41a65ea2004-08-13 03:55:05 +00001294 self._checker.check_output(e_msg, exc_msg,
Edward Loper34fcb142004-08-09 02:45:41 +00001295 self.optionflags)):
Tim Peters8485b562004-08-04 18:46:34 +00001296 self.report_success(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001297 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001298 else:
1299 self.report_failure(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001300 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001301 failures += 1
1302
1303 # Restore the option flags (in case they were modified)
1304 self.optionflags = original_optionflags
1305
1306 # Record and return the number of failures and tries.
1307 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001308 return failures, tries
1309
Tim Peters8485b562004-08-04 18:46:34 +00001310 def __record_outcome(self, test, f, t):
1311 """
1312 Record the fact that the given DocTest (`test`) generated `f`
1313 failures out of `t` tried examples.
1314 """
1315 f2, t2 = self._name2ft.get(test.name, (0,0))
1316 self._name2ft[test.name] = (f+f2, t+t2)
1317 self.failures += f
1318 self.tries += t
1319
1320 def run(self, test, compileflags=None, out=None, clear_globs=True):
1321 """
1322 Run the examples in `test`, and display the results using the
1323 writer function `out`.
1324
1325 The examples are run in the namespace `test.globs`. If
1326 `clear_globs` is true (the default), then this namespace will
1327 be cleared after the test runs, to help with garbage
1328 collection. If you would like to examine the namespace after
1329 the test completes, then use `clear_globs=False`.
1330
1331 `compileflags` gives the set of flags that should be used by
1332 the Python compiler when running the examples. If not
1333 specified, then it will default to the set of future-import
1334 flags that apply to `globs`.
1335
1336 The output of each example is checked using
1337 `DocTestRunner.check_output`, and the results are formatted by
1338 the `DocTestRunner.report_*` methods.
1339 """
1340 if compileflags is None:
1341 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001342
Tim Peters6c542b72004-08-09 16:43:36 +00001343 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001344 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001345 out = save_stdout.write
1346 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001347
Tim Peters6c542b72004-08-09 16:43:36 +00001348 # Patch pdb.set_trace to restore sys.stdout, so that interactive
1349 # debugging output is visible (not still redirected to self._fakeout).
1350 # Note that we run "the real" pdb.set_trace (captured at doctest
1351 # import time) in our replacement. Because the current run() may
1352 # run another doctest (and so on), the current pdb.set_trace may be
1353 # our set_trace function, which changes sys.stdout. If we called
1354 # a chain of those, we wouldn't be left with the save_stdout
1355 # *this* run() invocation wants.
Jim Fulton356fd192004-08-09 11:34:47 +00001356 def set_trace():
Tim Peters6c542b72004-08-09 16:43:36 +00001357 sys.stdout = save_stdout
Jim Fulton356fd192004-08-09 11:34:47 +00001358 real_pdb_set_trace()
1359
Tim Peters6c542b72004-08-09 16:43:36 +00001360 save_set_trace = pdb.set_trace
1361 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001362 try:
Tim Peters8485b562004-08-04 18:46:34 +00001363 return self.__run(test, compileflags, out)
1364 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001365 sys.stdout = save_stdout
1366 pdb.set_trace = save_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001367 if clear_globs:
1368 test.globs.clear()
1369
1370 #/////////////////////////////////////////////////////////////////
1371 # Summarization
1372 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001373 def summarize(self, verbose=None):
1374 """
Tim Peters8485b562004-08-04 18:46:34 +00001375 Print a summary of all the test cases that have been run by
1376 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1377 the total number of failed examples, and `t` is the total
1378 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001379
Tim Peters8485b562004-08-04 18:46:34 +00001380 The optional `verbose` argument controls how detailed the
1381 summary is. If the verbosity is not specified, then the
1382 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001383 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001384 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001385 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001386 notests = []
1387 passed = []
1388 failed = []
1389 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001390 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001391 name, (f, t) = x
1392 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001393 totalt += t
1394 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001395 if t == 0:
1396 notests.append(name)
1397 elif f == 0:
1398 passed.append( (name, t) )
1399 else:
1400 failed.append(x)
1401 if verbose:
1402 if notests:
1403 print len(notests), "items had no tests:"
1404 notests.sort()
1405 for thing in notests:
1406 print " ", thing
1407 if passed:
1408 print len(passed), "items passed all tests:"
1409 passed.sort()
1410 for thing, count in passed:
1411 print " %3d tests in %s" % (count, thing)
1412 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001413 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001414 print len(failed), "items had failures:"
1415 failed.sort()
1416 for thing, (f, t) in failed:
1417 print " %3d of %3d in %s" % (f, t, thing)
1418 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001419 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001420 print totalt - totalf, "passed and", totalf, "failed."
1421 if totalf:
1422 print "***Test Failed***", totalf, "failures."
1423 elif verbose:
1424 print "Test passed."
1425 return totalf, totalt
1426
Edward Loper34fcb142004-08-09 02:45:41 +00001427class OutputChecker:
1428 """
1429 A class used to check the whether the actual output from a doctest
1430 example matches the expected output. `OutputChecker` defines two
1431 methods: `check_output`, which compares a given pair of outputs,
1432 and returns true if they match; and `output_difference`, which
1433 returns a string describing the differences between two outputs.
1434 """
1435 def check_output(self, want, got, optionflags):
1436 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001437 Return True iff the actual output from an example (`got`)
1438 matches the expected output (`want`). These strings are
1439 always considered to match if they are identical; but
1440 depending on what option flags the test runner is using,
1441 several non-exact match types are also possible. See the
1442 documentation for `TestRunner` for more information about
1443 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001444 """
1445 # Handle the common case first, for efficiency:
1446 # if they're string-identical, always return true.
1447 if got == want:
1448 return True
1449
1450 # The values True and False replaced 1 and 0 as the return
1451 # value for boolean comparisons in Python 2.3.
1452 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1453 if (got,want) == ("True\n", "1\n"):
1454 return True
1455 if (got,want) == ("False\n", "0\n"):
1456 return True
1457
1458 # <BLANKLINE> can be used as a special sequence to signify a
1459 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1460 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1461 # Replace <BLANKLINE> in want with a blank line.
1462 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1463 '', want)
1464 # If a line in got contains only spaces, then remove the
1465 # spaces.
1466 got = re.sub('(?m)^\s*?$', '', got)
1467 if got == want:
1468 return True
1469
1470 # This flag causes doctest to ignore any differences in the
1471 # contents of whitespace strings. Note that this can be used
1472 # in conjunction with the ELLISPIS flag.
1473 if (optionflags & NORMALIZE_WHITESPACE):
1474 got = ' '.join(got.split())
1475 want = ' '.join(want.split())
1476 if got == want:
1477 return True
1478
1479 # The ELLIPSIS flag says to let the sequence "..." in `want`
1480 # match any substring in `got`. We implement this by
1481 # transforming `want` into a regular expression.
1482 if (optionflags & ELLIPSIS):
1483 # Escape any special regexp characters
1484 want_re = re.escape(want)
1485 # Replace ellipsis markers ('...') with .*
1486 want_re = want_re.replace(re.escape(ELLIPSIS_MARKER), '.*')
1487 # Require that it matches the entire string; and set the
1488 # re.DOTALL flag (with '(?s)').
1489 want_re = '(?s)^%s$' % want_re
1490 # Check if the `want_re` regexp matches got.
1491 if re.match(want_re, got):
1492 return True
1493
1494 # We didn't find any match; return false.
1495 return False
1496
1497 def output_difference(self, want, got, optionflags):
1498 """
1499 Return a string describing the differences between the
Edward Loper74bca7a2004-08-12 02:27:44 +00001500 expected output for an example (`want`) and the actual output
1501 (`got`). `optionflags` is the set of option flags used to
1502 compare `want` and `got`. `indent` is the indentation of the
1503 original example.
Edward Loper34fcb142004-08-09 02:45:41 +00001504 """
Edward Loper68ba9a62004-08-12 02:43:49 +00001505 # If <BLANKLINE>s are being used, then replace blank lines
1506 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001507 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001508 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001509
1510 # Check if we should use diff. Don't use diff if the actual
1511 # or expected outputs are too short, or if the expected output
1512 # contains an ellipsis marker.
1513 if ((optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and
1514 want.count('\n') > 2 and got.count('\n') > 2 and
1515 not (optionflags & ELLIPSIS and '...' in want)):
1516 # Split want & got into lines.
1517 want_lines = [l+'\n' for l in want.split('\n')]
1518 got_lines = [l+'\n' for l in got.split('\n')]
1519 # Use difflib to find their differences.
1520 if optionflags & UNIFIED_DIFF:
1521 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1522 fromfile='Expected', tofile='Got')
1523 kind = 'unified'
1524 elif optionflags & CONTEXT_DIFF:
1525 diff = difflib.context_diff(want_lines, got_lines, n=2,
1526 fromfile='Expected', tofile='Got')
1527 kind = 'context'
1528 else:
1529 assert 0, 'Bad diff option'
1530 # Remove trailing whitespace on diff output.
1531 diff = [line.rstrip() + '\n' for line in diff]
1532 return _tag_msg("Differences (" + kind + " diff)",
1533 ''.join(diff))
1534
1535 # If we're not using diff, then simply list the expected
1536 # output followed by the actual output.
1537 return (_tag_msg("Expected", want or "Nothing") +
1538 _tag_msg("Got", got))
1539
Tim Peters19397e52004-08-06 22:02:59 +00001540class DocTestFailure(Exception):
1541 """A DocTest example has failed in debugging mode.
1542
1543 The exception instance has variables:
1544
1545 - test: the DocTest object being run
1546
1547 - excample: the Example object that failed
1548
1549 - got: the actual output
1550 """
1551 def __init__(self, test, example, got):
1552 self.test = test
1553 self.example = example
1554 self.got = got
1555
1556 def __str__(self):
1557 return str(self.test)
1558
1559class UnexpectedException(Exception):
1560 """A DocTest example has encountered an unexpected exception
1561
1562 The exception instance has variables:
1563
1564 - test: the DocTest object being run
1565
1566 - excample: the Example object that failed
1567
1568 - exc_info: the exception info
1569 """
1570 def __init__(self, test, example, exc_info):
1571 self.test = test
1572 self.example = example
1573 self.exc_info = exc_info
1574
1575 def __str__(self):
1576 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001577
Tim Peters19397e52004-08-06 22:02:59 +00001578class DebugRunner(DocTestRunner):
1579 r"""Run doc tests but raise an exception as soon as there is a failure.
1580
1581 If an unexpected exception occurs, an UnexpectedException is raised.
1582 It contains the test, the example, and the original exception:
1583
1584 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001585 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1586 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001587 >>> try:
1588 ... runner.run(test)
1589 ... except UnexpectedException, failure:
1590 ... pass
1591
1592 >>> failure.test is test
1593 True
1594
1595 >>> failure.example.want
1596 '42\n'
1597
1598 >>> exc_info = failure.exc_info
1599 >>> raise exc_info[0], exc_info[1], exc_info[2]
1600 Traceback (most recent call last):
1601 ...
1602 KeyError
1603
1604 We wrap the original exception to give the calling application
1605 access to the test and example information.
1606
1607 If the output doesn't match, then a DocTestFailure is raised:
1608
Edward Lopera1ef6112004-08-09 16:14:41 +00001609 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001610 ... >>> x = 1
1611 ... >>> x
1612 ... 2
1613 ... ''', {}, 'foo', 'foo.py', 0)
1614
1615 >>> try:
1616 ... runner.run(test)
1617 ... except DocTestFailure, failure:
1618 ... pass
1619
1620 DocTestFailure objects provide access to the test:
1621
1622 >>> failure.test is test
1623 True
1624
1625 As well as to the example:
1626
1627 >>> failure.example.want
1628 '2\n'
1629
1630 and the actual output:
1631
1632 >>> failure.got
1633 '1\n'
1634
1635 If a failure or error occurs, the globals are left intact:
1636
1637 >>> del test.globs['__builtins__']
1638 >>> test.globs
1639 {'x': 1}
1640
Edward Lopera1ef6112004-08-09 16:14:41 +00001641 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001642 ... >>> x = 2
1643 ... >>> raise KeyError
1644 ... ''', {}, 'foo', 'foo.py', 0)
1645
1646 >>> runner.run(test)
1647 Traceback (most recent call last):
1648 ...
1649 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001650
Tim Peters19397e52004-08-06 22:02:59 +00001651 >>> del test.globs['__builtins__']
1652 >>> test.globs
1653 {'x': 2}
1654
1655 But the globals are cleared if there is no error:
1656
Edward Lopera1ef6112004-08-09 16:14:41 +00001657 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001658 ... >>> x = 2
1659 ... ''', {}, 'foo', 'foo.py', 0)
1660
1661 >>> runner.run(test)
1662 (0, 1)
1663
1664 >>> test.globs
1665 {}
1666
1667 """
1668
1669 def run(self, test, compileflags=None, out=None, clear_globs=True):
1670 r = DocTestRunner.run(self, test, compileflags, out, False)
1671 if clear_globs:
1672 test.globs.clear()
1673 return r
1674
1675 def report_unexpected_exception(self, out, test, example, exc_info):
1676 raise UnexpectedException(test, example, exc_info)
1677
1678 def report_failure(self, out, test, example, got):
1679 raise DocTestFailure(test, example, got)
1680
Tim Peters8485b562004-08-04 18:46:34 +00001681######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001682## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001683######################################################################
1684# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001685
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001686def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001687 report=True, optionflags=0, extraglobs=None,
1688 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001689 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001690 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001691
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001692 Test examples in docstrings in functions and classes reachable
1693 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001694 with m.__doc__. Unless isprivate is specified, private names
1695 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001696
1697 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001698 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001699 function and class docstrings are tested even if the name is private;
1700 strings are tested directly, as if they were docstrings.
1701
1702 Return (#failures, #tests).
1703
1704 See doctest.__doc__ for an overview.
1705
1706 Optional keyword arg "name" gives the name of the module; by default
1707 use m.__name__.
1708
1709 Optional keyword arg "globs" gives a dict to be used as the globals
1710 when executing examples; by default, use m.__dict__. A copy of this
1711 dict is actually used for each docstring, so that each docstring's
1712 examples start with a clean slate.
1713
Tim Peters8485b562004-08-04 18:46:34 +00001714 Optional keyword arg "extraglobs" gives a dictionary that should be
1715 merged into the globals that are used to execute examples. By
1716 default, no extra globals are used. This is new in 2.4.
1717
Tim Peters8a7d2d52001-01-16 07:10:57 +00001718 Optional keyword arg "verbose" prints lots of stuff if true, prints
1719 only failures if false; by default, it's true iff "-v" is in sys.argv.
1720
Tim Peters8a7d2d52001-01-16 07:10:57 +00001721 Optional keyword arg "report" prints a summary at the end when true,
1722 else prints nothing at the end. In verbose mode, the summary is
1723 detailed, else very brief (in fact, empty if all tests passed).
1724
Tim Peters6ebe61f2003-06-27 20:48:05 +00001725 Optional keyword arg "optionflags" or's together module constants,
1726 and defaults to 0. This is new in 2.3. Possible values:
1727
1728 DONT_ACCEPT_TRUE_FOR_1
1729 By default, if an expected output block contains just "1",
1730 an actual output block containing just "True" is considered
1731 to be a match, and similarly for "0" versus "False". When
1732 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1733 is allowed.
1734
Tim Peters8485b562004-08-04 18:46:34 +00001735 DONT_ACCEPT_BLANKLINE
1736 By default, if an expected output block contains a line
1737 containing only the string "<BLANKLINE>", then that line
1738 will match a blank line in the actual output. When
1739 DONT_ACCEPT_BLANKLINE is specified, this substitution is
1740 not allowed.
1741
1742 NORMALIZE_WHITESPACE
1743 When NORMALIZE_WHITESPACE is specified, all sequences of
1744 whitespace are treated as equal. I.e., any sequence of
1745 whitespace within the expected output will match any
1746 sequence of whitespace within the actual output.
1747
1748 ELLIPSIS
1749 When ELLIPSIS is specified, then an ellipsis marker
1750 ("...") in the expected output can match any substring in
1751 the actual output.
1752
1753 UNIFIED_DIFF
1754 When UNIFIED_DIFF is specified, failures that involve
1755 multi-line expected and actual outputs will be displayed
1756 using a unified diff.
1757
1758 CONTEXT_DIFF
1759 When CONTEXT_DIFF is specified, failures that involve
1760 multi-line expected and actual outputs will be displayed
1761 using a context diff.
Tim Peters19397e52004-08-06 22:02:59 +00001762
1763 Optional keyword arg "raise_on_error" raises an exception on the
1764 first unexpected exception or failure. This allows failures to be
1765 post-mortem debugged.
1766
Tim Petersf727c6c2004-08-08 01:48:59 +00001767 Deprecated in Python 2.4:
1768 Optional keyword arg "isprivate" specifies a function used to
1769 determine whether a name is private. The default function is
1770 treat all functions as public. Optionally, "isprivate" can be
1771 set to doctest.is_private to skip over functions marked as private
1772 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001773 """
1774
1775 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001776 Advanced tomfoolery: testmod runs methods of a local instance of
1777 class doctest.Tester, then merges the results into (or creates)
1778 global Tester instance doctest.master. Methods of doctest.master
1779 can be called directly too, if you want to do something unusual.
1780 Passing report=0 to testmod is especially useful then, to delay
1781 displaying a summary. Invoke doctest.master.summarize(verbose)
1782 when you're done fiddling.
1783 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001784 if isprivate is not None:
1785 warnings.warn("the isprivate argument is deprecated; "
1786 "examine DocTestFinder.find() lists instead",
1787 DeprecationWarning)
1788
Tim Peters8485b562004-08-04 18:46:34 +00001789 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001790 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001791 # DWA - m will still be None if this wasn't invoked from the command
1792 # line, in which case the following TypeError is about as good an error
1793 # as we should expect
1794 m = sys.modules.get('__main__')
1795
Tim Peters8485b562004-08-04 18:46:34 +00001796 # Check that we were actually given a module.
1797 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001798 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001799
1800 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001801 if name is None:
1802 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001803
1804 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001805 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001806
1807 if raise_on_error:
1808 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1809 else:
1810 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1811
Tim Peters8485b562004-08-04 18:46:34 +00001812 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1813 runner.run(test)
1814
Tim Peters8a7d2d52001-01-16 07:10:57 +00001815 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001816 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001817
Tim Peters8485b562004-08-04 18:46:34 +00001818 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001819
Tim Peters8485b562004-08-04 18:46:34 +00001820def run_docstring_examples(f, globs, verbose=False, name="NoName",
1821 compileflags=None, optionflags=0):
1822 """
1823 Test examples in the given object's docstring (`f`), using `globs`
1824 as globals. Optional argument `name` is used in failure messages.
1825 If the optional argument `verbose` is true, then generate output
1826 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001827
Tim Peters8485b562004-08-04 18:46:34 +00001828 `compileflags` gives the set of flags that should be used by the
1829 Python compiler when running the examples. If not specified, then
1830 it will default to the set of future-import flags that apply to
1831 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001832
Tim Peters8485b562004-08-04 18:46:34 +00001833 Optional keyword arg `optionflags` specifies options for the
1834 testing and output. See the documentation for `testmod` for more
1835 information.
1836 """
1837 # Find, parse, and run all tests in the given module.
1838 finder = DocTestFinder(verbose=verbose, recurse=False)
1839 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1840 for test in finder.find(f, name, globs=globs):
1841 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001842
Tim Peters8485b562004-08-04 18:46:34 +00001843######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001844## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001845######################################################################
1846# This is provided only for backwards compatibility. It's not
1847# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001848
Tim Peters8485b562004-08-04 18:46:34 +00001849class Tester:
1850 def __init__(self, mod=None, globs=None, verbose=None,
1851 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001852
1853 warnings.warn("class Tester is deprecated; "
1854 "use class doctest.DocTestRunner instead",
1855 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001856 if mod is None and globs is None:
1857 raise TypeError("Tester.__init__: must specify mod or globs")
1858 if mod is not None and not _ismodule(mod):
1859 raise TypeError("Tester.__init__: mod must be a module; %r" %
1860 (mod,))
1861 if globs is None:
1862 globs = mod.__dict__
1863 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001864
Tim Peters8485b562004-08-04 18:46:34 +00001865 self.verbose = verbose
1866 self.isprivate = isprivate
1867 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001868 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001869 self.testrunner = DocTestRunner(verbose=verbose,
1870 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001871
Tim Peters8485b562004-08-04 18:46:34 +00001872 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001873 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001874 if self.verbose:
1875 print "Running string", name
1876 (f,t) = self.testrunner.run(test)
1877 if self.verbose:
1878 print f, "of", t, "examples failed in string", name
1879 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001880
Tim Petersf3f57472004-08-08 06:11:48 +00001881 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001882 f = t = 0
1883 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001884 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001885 for test in tests:
1886 (f2, t2) = self.testrunner.run(test)
1887 (f,t) = (f+f2, t+t2)
1888 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001889
Tim Peters8485b562004-08-04 18:46:34 +00001890 def rundict(self, d, name, module=None):
1891 import new
1892 m = new.module(name)
1893 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001894 if module is None:
1895 module = False
1896 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001897
Tim Peters8485b562004-08-04 18:46:34 +00001898 def run__test__(self, d, name):
1899 import new
1900 m = new.module(name)
1901 m.__test__ = d
1902 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001903
Tim Peters8485b562004-08-04 18:46:34 +00001904 def summarize(self, verbose=None):
1905 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001906
Tim Peters8485b562004-08-04 18:46:34 +00001907 def merge(self, other):
1908 d = self.testrunner._name2ft
1909 for name, (f, t) in other.testrunner._name2ft.items():
1910 if name in d:
1911 print "*** Tester.merge: '" + name + "' in both" \
1912 " testers; summing outcomes."
1913 f2, t2 = d[name]
1914 f = f + f2
1915 t = t + t2
1916 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001917
Tim Peters8485b562004-08-04 18:46:34 +00001918######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001919## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001920######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001921
Tim Peters19397e52004-08-06 22:02:59 +00001922class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001923
Edward Loper34fcb142004-08-09 02:45:41 +00001924 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
1925 checker=None):
Jim Fultona643b652004-07-14 19:06:50 +00001926 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00001927 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00001928 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00001929 self._dt_test = test
1930 self._dt_setUp = setUp
1931 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00001932
Jim Fultona643b652004-07-14 19:06:50 +00001933 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00001934 if self._dt_setUp is not None:
1935 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00001936
1937 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00001938 if self._dt_tearDown is not None:
1939 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00001940
1941 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00001942 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00001943 old = sys.stdout
1944 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00001945 runner = DocTestRunner(optionflags=self._dt_optionflags,
1946 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001947
Jim Fultona643b652004-07-14 19:06:50 +00001948 try:
Tim Peters19397e52004-08-06 22:02:59 +00001949 runner.DIVIDER = "-"*70
1950 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00001951 finally:
1952 sys.stdout = old
1953
1954 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00001955 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00001956
Tim Peters19397e52004-08-06 22:02:59 +00001957 def format_failure(self, err):
1958 test = self._dt_test
1959 if test.lineno is None:
1960 lineno = 'unknown line number'
1961 else:
1962 lineno = 'line %s' % test.lineno
1963 lname = '.'.join(test.name.split('.')[-1:])
1964 return ('Failed doctest test for %s\n'
1965 ' File "%s", line %s, in %s\n\n%s'
1966 % (test.name, test.filename, lineno, lname, err)
1967 )
1968
1969 def debug(self):
1970 r"""Run the test case without results and without catching exceptions
1971
1972 The unit test framework includes a debug method on test cases
1973 and test suites to support post-mortem debugging. The test code
1974 is run in such a way that errors are not caught. This way a
1975 caller can catch the errors and initiate post-mortem debugging.
1976
1977 The DocTestCase provides a debug method that raises
1978 UnexpectedException errors if there is an unexepcted
1979 exception:
1980
Edward Lopera1ef6112004-08-09 16:14:41 +00001981 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00001982 ... {}, 'foo', 'foo.py', 0)
1983 >>> case = DocTestCase(test)
1984 >>> try:
1985 ... case.debug()
1986 ... except UnexpectedException, failure:
1987 ... pass
1988
1989 The UnexpectedException contains the test, the example, and
1990 the original exception:
1991
1992 >>> failure.test is test
1993 True
1994
1995 >>> failure.example.want
1996 '42\n'
1997
1998 >>> exc_info = failure.exc_info
1999 >>> raise exc_info[0], exc_info[1], exc_info[2]
2000 Traceback (most recent call last):
2001 ...
2002 KeyError
2003
2004 If the output doesn't match, then a DocTestFailure is raised:
2005
Edward Lopera1ef6112004-08-09 16:14:41 +00002006 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002007 ... >>> x = 1
2008 ... >>> x
2009 ... 2
2010 ... ''', {}, 'foo', 'foo.py', 0)
2011 >>> case = DocTestCase(test)
2012
2013 >>> try:
2014 ... case.debug()
2015 ... except DocTestFailure, failure:
2016 ... pass
2017
2018 DocTestFailure objects provide access to the test:
2019
2020 >>> failure.test is test
2021 True
2022
2023 As well as to the example:
2024
2025 >>> failure.example.want
2026 '2\n'
2027
2028 and the actual output:
2029
2030 >>> failure.got
2031 '1\n'
2032
2033 """
2034
Edward Loper34fcb142004-08-09 02:45:41 +00002035 runner = DebugRunner(optionflags=self._dt_optionflags,
2036 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002037 runner.run(self._dt_test, out=nooutput)
Jim Fultona643b652004-07-14 19:06:50 +00002038
2039 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002040 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002041
2042 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002043 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002044 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2045
2046 __str__ = __repr__
2047
2048 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002049 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002050
Tim Peters19397e52004-08-06 22:02:59 +00002051def nooutput(*args):
2052 pass
Jim Fultona643b652004-07-14 19:06:50 +00002053
Tim Peters19397e52004-08-06 22:02:59 +00002054def DocTestSuite(module=None, globs=None, extraglobs=None,
2055 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002056 setUp=lambda: None, tearDown=lambda: None,
2057 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002058 """
Tim Peters19397e52004-08-06 22:02:59 +00002059 Convert doctest tests for a mudule to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002060
Tim Peters19397e52004-08-06 22:02:59 +00002061 This converts each documentation string in a module that
2062 contains doctest tests to a unittest test case. If any of the
2063 tests in a doc string fail, then the test case fails. An exception
2064 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002065 (sometimes approximate) line number.
2066
Tim Peters19397e52004-08-06 22:02:59 +00002067 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002068 can be either a module or a module name.
2069
2070 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002071 """
Jim Fultona643b652004-07-14 19:06:50 +00002072
Tim Peters8485b562004-08-04 18:46:34 +00002073 if test_finder is None:
2074 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002075
Tim Peters19397e52004-08-06 22:02:59 +00002076 module = _normalize_module(module)
2077 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2078 if globs is None:
2079 globs = module.__dict__
2080 if not tests: # [XX] why do we want to do this?
2081 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002082
2083 tests.sort()
2084 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002085 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002086 if len(test.examples) == 0:
2087 continue
Tim Peters8485b562004-08-04 18:46:34 +00002088 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002089 filename = module.__file__
2090 if filename.endswith(".pyc"):
2091 filename = filename[:-1]
2092 elif filename.endswith(".pyo"):
2093 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002094 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002095 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2096 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002097
2098 return suite
2099
2100class DocFileCase(DocTestCase):
2101
2102 def id(self):
2103 return '_'.join(self._dt_test.name.split('.'))
2104
2105 def __repr__(self):
2106 return self._dt_test.filename
2107 __str__ = __repr__
2108
2109 def format_failure(self, err):
2110 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2111 % (self._dt_test.name, self._dt_test.filename, err)
2112 )
2113
2114def DocFileTest(path, package=None, globs=None,
2115 setUp=None, tearDown=None,
2116 optionflags=0):
2117 package = _normalize_module(package)
2118 name = path.split('/')[-1]
2119 dir = os.path.split(package.__file__)[0]
2120 path = os.path.join(dir, *(path.split('/')))
2121 doc = open(path).read()
2122
2123 if globs is None:
2124 globs = {}
2125
Edward Lopera1ef6112004-08-09 16:14:41 +00002126 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002127
2128 return DocFileCase(test, optionflags, setUp, tearDown)
2129
2130def DocFileSuite(*paths, **kw):
2131 """Creates a suite of doctest files.
2132
2133 One or more text file paths are given as strings. These should
2134 use "/" characters to separate path segments. Paths are relative
2135 to the directory of the calling module, or relative to the package
2136 passed as a keyword argument.
2137
2138 A number of options may be provided as keyword arguments:
2139
2140 package
2141 The name of a Python package. Text-file paths will be
2142 interpreted relative to the directory containing this package.
2143 The package may be supplied as a package object or as a dotted
2144 package name.
2145
2146 setUp
2147 The name of a set-up function. This is called before running the
2148 tests in each file.
2149
2150 tearDown
2151 The name of a tear-down function. This is called after running the
2152 tests in each file.
2153
2154 globs
2155 A dictionary containing initial global variables for the tests.
2156 """
2157 suite = unittest.TestSuite()
2158
2159 # We do this here so that _normalize_module is called at the right
2160 # level. If it were called in DocFileTest, then this function
2161 # would be the caller and we might guess the package incorrectly.
2162 kw['package'] = _normalize_module(kw.get('package'))
2163
2164 for path in paths:
2165 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002166
Tim Petersdb3756d2003-06-29 05:30:48 +00002167 return suite
2168
Tim Peters8485b562004-08-04 18:46:34 +00002169######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002170## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002171######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002172
Tim Peters19397e52004-08-06 22:02:59 +00002173def script_from_examples(s):
2174 r"""Extract script from text with examples.
2175
2176 Converts text with examples to a Python script. Example input is
2177 converted to regular code. Example output and all other words
2178 are converted to comments:
2179
2180 >>> text = '''
2181 ... Here are examples of simple math.
2182 ...
2183 ... Python has super accurate integer addition
2184 ...
2185 ... >>> 2 + 2
2186 ... 5
2187 ...
2188 ... And very friendly error messages:
2189 ...
2190 ... >>> 1/0
2191 ... To Infinity
2192 ... And
2193 ... Beyond
2194 ...
2195 ... You can use logic if you want:
2196 ...
2197 ... >>> if 0:
2198 ... ... blah
2199 ... ... blah
2200 ... ...
2201 ...
2202 ... Ho hum
2203 ... '''
2204
2205 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002206 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002207 #
Edward Lopera5db6002004-08-12 02:41:30 +00002208 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002209 #
2210 2 + 2
2211 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002212 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002213 #
Edward Lopera5db6002004-08-12 02:41:30 +00002214 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002215 #
2216 1/0
2217 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002218 ## To Infinity
2219 ## And
2220 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002221 #
Edward Lopera5db6002004-08-12 02:41:30 +00002222 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002223 #
2224 if 0:
2225 blah
2226 blah
2227 <BLANKLINE>
2228 #
Edward Lopera5db6002004-08-12 02:41:30 +00002229 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002230 """
2231
Edward Lopera1ef6112004-08-09 16:14:41 +00002232 return DocTestParser().get_program(s)
Tim Peters19397e52004-08-06 22:02:59 +00002233
Tim Peters8485b562004-08-04 18:46:34 +00002234def _want_comment(example):
2235 """
Tim Peters19397e52004-08-06 22:02:59 +00002236 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002237 """
Jim Fultona643b652004-07-14 19:06:50 +00002238 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002239 want = example.want
2240 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002241 if want[-1] == '\n':
2242 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002243 want = "\n# ".join(want.split("\n"))
2244 want = "\n# Expected:\n# %s" % want
2245 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002246
2247def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002248 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002249
2250 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002251 test to be debugged and the name (within the module) of the object
2252 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002253 """
Tim Peters8485b562004-08-04 18:46:34 +00002254 module = _normalize_module(module)
2255 tests = DocTestFinder().find(module)
2256 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002257 if not test:
2258 raise ValueError(name, "not found in tests")
2259 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002260 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002261 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002262
Jim Fultona643b652004-07-14 19:06:50 +00002263def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002264 """Debug a single doctest docstring, in argument `src`'"""
2265 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002266 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002267
Jim Fultona643b652004-07-14 19:06:50 +00002268def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002269 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002270 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002271
Tim Petersdb3756d2003-06-29 05:30:48 +00002272 srcfilename = tempfile.mktemp("doctestdebug.py")
Tim Peters8485b562004-08-04 18:46:34 +00002273 f = open(srcfilename, 'w')
2274 f.write(src)
2275 f.close()
2276
Jim Fultona643b652004-07-14 19:06:50 +00002277 if globs:
2278 globs = globs.copy()
2279 else:
2280 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002281
Tim Peters8485b562004-08-04 18:46:34 +00002282 if pm:
2283 try:
2284 execfile(srcfilename, globs, globs)
2285 except:
2286 print sys.exc_info()[1]
2287 pdb.post_mortem(sys.exc_info()[2])
2288 else:
2289 # Note that %r is vital here. '%s' instead can, e.g., cause
2290 # backslashes to get treated as metacharacters on Windows.
2291 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002292
Jim Fultona643b652004-07-14 19:06:50 +00002293def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002294 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002295
2296 Provide the module (or dotted name of the module) containing the
2297 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002298 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002299 """
Tim Peters8485b562004-08-04 18:46:34 +00002300 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002301 testsrc = testsource(module, name)
2302 debug_script(testsrc, pm, module.__dict__)
2303
Tim Peters8485b562004-08-04 18:46:34 +00002304######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002305## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002306######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002307class _TestClass:
2308 """
2309 A pointless class, for sanity-checking of docstring testing.
2310
2311 Methods:
2312 square()
2313 get()
2314
2315 >>> _TestClass(13).get() + _TestClass(-12).get()
2316 1
2317 >>> hex(_TestClass(13).square().get())
2318 '0xa9'
2319 """
2320
2321 def __init__(self, val):
2322 """val -> _TestClass object with associated value val.
2323
2324 >>> t = _TestClass(123)
2325 >>> print t.get()
2326 123
2327 """
2328
2329 self.val = val
2330
2331 def square(self):
2332 """square() -> square TestClass's associated value
2333
2334 >>> _TestClass(13).square().get()
2335 169
2336 """
2337
2338 self.val = self.val ** 2
2339 return self
2340
2341 def get(self):
2342 """get() -> return TestClass's associated value.
2343
2344 >>> x = _TestClass(-42)
2345 >>> print x.get()
2346 -42
2347 """
2348
2349 return self.val
2350
2351__test__ = {"_TestClass": _TestClass,
2352 "string": r"""
2353 Example of a string object, searched as-is.
2354 >>> x = 1; y = 2
2355 >>> x + y, x * y
2356 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002357 """,
2358 "bool-int equivalence": r"""
2359 In 2.2, boolean expressions displayed
2360 0 or 1. By default, we still accept
2361 them. This can be disabled by passing
2362 DONT_ACCEPT_TRUE_FOR_1 to the new
2363 optionflags argument.
2364 >>> 4 == 4
2365 1
2366 >>> 4 == 4
2367 True
2368 >>> 4 > 4
2369 0
2370 >>> 4 > 4
2371 False
2372 """,
Tim Peters8485b562004-08-04 18:46:34 +00002373 "blank lines": r"""
2374 Blank lines can be marked with <BLANKLINE>:
2375 >>> print 'foo\n\nbar\n'
2376 foo
2377 <BLANKLINE>
2378 bar
2379 <BLANKLINE>
2380 """,
2381 }
2382# "ellipsis": r"""
2383# If the ellipsis flag is used, then '...' can be used to
2384# elide substrings in the desired output:
2385# >>> print range(1000)
2386# [0, 1, 2, ..., 999]
2387# """,
2388# "whitespace normalization": r"""
2389# If the whitespace normalization flag is used, then
2390# differences in whitespace are ignored.
2391# >>> print range(30)
2392# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2393# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2394# 27, 28, 29]
2395# """,
2396# }
2397
2398def test1(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002399>>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2400... "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002401>>> from doctest import Tester
2402>>> t = Tester(globs={'x': 42}, verbose=0)
2403>>> t.runstring(r'''
2404... >>> x = x * 2
2405... >>> print x
2406... 42
2407... ''', 'XYZ')
2408**********************************************************************
2409Failure in example: print x
2410from line #2 of XYZ
2411Expected: 42
2412Got: 84
2413(1, 2)
2414>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2415(0, 2)
2416>>> t.summarize()
2417**********************************************************************
24181 items had failures:
2419 1 of 2 in XYZ
2420***Test Failed*** 1 failures.
2421(1, 4)
2422>>> t.summarize(verbose=1)
24231 items passed all tests:
2424 2 tests in example2
2425**********************************************************************
24261 items had failures:
2427 1 of 2 in XYZ
24284 tests in 2 items.
24293 passed and 1 failed.
2430***Test Failed*** 1 failures.
2431(1, 4)
2432"""
2433
2434def test2(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002435 >>> warnings.filterwarnings("ignore", "class Tester",
2436 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002437 >>> t = Tester(globs={}, verbose=1)
2438 >>> test = r'''
2439 ... # just an example
2440 ... >>> x = 1 + 2
2441 ... >>> x
2442 ... 3
2443 ... '''
2444 >>> t.runstring(test, "Example")
2445 Running string Example
2446 Trying: x = 1 + 2
2447 Expecting: nothing
2448 ok
2449 Trying: x
2450 Expecting: 3
2451 ok
2452 0 of 2 examples failed in string Example
2453 (0, 2)
2454"""
2455def test3(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002456 >>> warnings.filterwarnings("ignore", "class Tester",
2457 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002458 >>> t = Tester(globs={}, verbose=0)
2459 >>> def _f():
2460 ... '''Trivial docstring example.
2461 ... >>> assert 2 == 2
2462 ... '''
2463 ... return 32
2464 ...
2465 >>> t.rundoc(_f) # expect 0 failures in 1 example
2466 (0, 1)
2467"""
2468def test4(): """
2469 >>> import new
2470 >>> m1 = new.module('_m1')
2471 >>> m2 = new.module('_m2')
2472 >>> test_data = \"""
2473 ... def _f():
2474 ... '''>>> assert 1 == 1
2475 ... '''
2476 ... def g():
2477 ... '''>>> assert 2 != 1
2478 ... '''
2479 ... class H:
2480 ... '''>>> assert 2 > 1
2481 ... '''
2482 ... def bar(self):
2483 ... '''>>> assert 1 < 2
2484 ... '''
2485 ... \"""
2486 >>> exec test_data in m1.__dict__
2487 >>> exec test_data in m2.__dict__
2488 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2489
2490 Tests that objects outside m1 are excluded:
2491
Tim Peters3ddd60a2004-08-08 02:43:33 +00002492 >>> warnings.filterwarnings("ignore", "class Tester",
2493 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002494 >>> t = Tester(globs={}, verbose=0)
Tim Petersf727c6c2004-08-08 01:48:59 +00002495 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Tim Peters8485b562004-08-04 18:46:34 +00002496 (0, 4)
2497
Tim Petersf727c6c2004-08-08 01:48:59 +00002498 Once more, not excluding stuff outside m1:
Tim Peters8485b562004-08-04 18:46:34 +00002499
2500 >>> t = Tester(globs={}, verbose=0)
2501 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2502 (0, 8)
2503
2504 The exclusion of objects from outside the designated module is
2505 meant to be invoked automagically by testmod.
2506
Tim Petersf727c6c2004-08-08 01:48:59 +00002507 >>> testmod(m1, verbose=False)
2508 (0, 4)
Tim Peters8485b562004-08-04 18:46:34 +00002509"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002510
2511def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002512 #import doctest
2513 #doctest.testmod(doctest, verbose=False,
2514 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2515 # UNIFIED_DIFF)
2516 #print '~'*70
2517 r = unittest.TextTestRunner()
2518 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002519
2520if __name__ == "__main__":
2521 _test()