blob: 43f21b2e1c6c02915f2f9f2d073d3525f658dd66 [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8485b562004-08-04 18:46:34 +00002# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
Tim Peters19397e52004-08-06 22:02:59 +00003# Major enhancements and refactoring by:
Tim Peters8485b562004-08-04 18:46:34 +00004# Jim Fulton
5# Edward Loper
Tim Peters8a7d2d52001-01-16 07:10:57 +00006
7# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
8
Martin v. Löwis92816de2004-05-31 19:01:00 +00009r"""Module doctest -- a framework for running examples in docstrings.
Tim Peters8a7d2d52001-01-16 07:10:57 +000010
11NORMAL USAGE
12
Tim Peters80e53142004-08-09 04:34:45 +000013In simplest use, end each module M to be tested with:
Tim Peters8a7d2d52001-01-16 07:10:57 +000014
15def _test():
Tim Peters80e53142004-08-09 04:34:45 +000016 import doctest
17 return doctest.testmod()
Tim Peters8a7d2d52001-01-16 07:10:57 +000018
19if __name__ == "__main__":
20 _test()
21
22Then running the module as a script will cause the examples in the
23docstrings to get executed and verified:
24
25python M.py
26
27This won't display anything unless an example fails, in which case the
28failing example(s) and the cause(s) of the failure(s) are printed to stdout
29(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
30line of output is "Test failed.".
31
32Run it with the -v switch instead:
33
34python M.py -v
35
36and a detailed report of all examples tried is printed to stdout, along
37with assorted summaries at the end.
38
Tim Peters80e53142004-08-09 04:34:45 +000039You can force verbose mode by passing "verbose=True" to testmod, or prohibit
40it by passing "verbose=False". In either of those cases, sys.argv is not
Tim Peters8a7d2d52001-01-16 07:10:57 +000041examined by testmod.
42
43In any case, testmod returns a 2-tuple of ints (f, t), where f is the
44number of docstring examples that failed and t is the total number of
45docstring examples attempted.
46
Tim Peters80e53142004-08-09 04:34:45 +000047There are a variety of other ways to run doctests, including integration
48with the unittest framework, and support for running non-Python text
49files containing doctests. There are also many ways to override parts
50of doctest's default behaviors. See the Library Reference Manual for
51details.
52
Tim Peters8a7d2d52001-01-16 07:10:57 +000053
54WHICH DOCSTRINGS ARE EXAMINED?
55
56+ M.__doc__.
57
58+ f.__doc__ for all functions f in M.__dict__.values(), except those
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000059 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000060
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000061+ C.__doc__ for all classes C in M.__dict__.values(), except those
62 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000063
64+ If M.__test__ exists and "is true", it must be a dict, and
65 each entry maps a (string) name to a function object, class object, or
66 string. Function and class object docstrings found from M.__test__
Tim Peters80e53142004-08-09 04:34:45 +000067 are searched, and strings are searched directly as if they were docstrings.
68 In output, a key K in M.__test__ appears with name
Tim Peters8a7d2d52001-01-16 07:10:57 +000069 <name of M>.__test__.K
70
71Any classes found are recursively searched similarly, to test docstrings in
Tim Peters80e53142004-08-09 04:34:45 +000072their contained methods and nested classes.
Tim Peters8a7d2d52001-01-16 07:10:57 +000073
Tim Peters8a7d2d52001-01-16 07:10:57 +000074
Tim Peters8a7d2d52001-01-16 07:10:57 +000075WHAT'S THE EXECUTION CONTEXT?
76
77By default, each time testmod finds a docstring to test, it uses a *copy*
78of M's globals (so that running tests on a module doesn't change the
79module's real globals, and so that one test in M can't leave behind crumbs
80that accidentally allow another test to work). This means examples can
81freely use any names defined at top-level in M. It also means that sloppy
82imports (see above) can cause examples in external docstrings to use
83globals inappropriate for them.
84
85You can force use of your own dict as the execution context by passing
86"globs=your_dict" to testmod instead. Presumably this would be a copy of
87M.__dict__ merged with the globals from other imported modules.
88
89
Tim Peters8a7d2d52001-01-16 07:10:57 +000090WHAT ABOUT EXCEPTIONS?
91
92No problem, as long as the only output generated by the example is the
93traceback itself. For example:
94
Tim Peters60e23f42001-02-14 00:43:21 +000095 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +000096 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +000097 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +000098 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +000099 >>>
100
Tim Peters80e53142004-08-09 04:34:45 +0000101Note that only the exception type and value are compared.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000102
103
Tim Peters80e53142004-08-09 04:34:45 +0000104SO WHAT DOES A DOCTEST EXAMPLE LOOK LIKE ALREADY!?
Tim Peters8a7d2d52001-01-16 07:10:57 +0000105
106Oh ya. It's easy! In most cases a copy-and-paste of an interactive
107console session works fine -- just make sure the leading whitespace is
108rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
109right, but doctest is not in the business of guessing what you think a tab
110means).
111
112 >>> # comments are ignored
113 >>> x = 12
114 >>> x
115 12
116 >>> if x == 13:
117 ... print "yes"
118 ... else:
119 ... print "no"
120 ... print "NO"
121 ... print "NO!!!"
122 ...
123 no
124 NO
125 NO!!!
126 >>>
127
128Any expected output must immediately follow the final ">>>" or "..." line
129containing the code, and the expected output (if any) extends to the next
130">>>" or all-whitespace line. That's it.
131
132Bummers:
133
Tim Peters8a7d2d52001-01-16 07:10:57 +0000134+ Output to stdout is captured, but not output to stderr (exception
135 tracebacks are captured via a different means).
136
Martin v. Löwis92816de2004-05-31 19:01:00 +0000137+ If you continue a line via backslashing in an interactive session,
138 or for any other reason use a backslash, you should use a raw
139 docstring, which will preserve your backslahses exactly as you type
140 them:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000141
Tim Peters4e0e1b62004-07-07 20:54:48 +0000142 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000143 ... r'''Backslashes in a raw docstring: m\n'''
144 >>> print f.__doc__
145 Backslashes in a raw docstring: m\n
Tim Peters8a7d2d52001-01-16 07:10:57 +0000146
Martin v. Löwis92816de2004-05-31 19:01:00 +0000147 Otherwise, the backslash will be interpreted as part of the string.
148 E.g., the "\n" above would be interpreted as a newline character.
149 Alternatively, you can double each backslash in the doctest version
150 (and not use a raw string):
151
Tim Peters4e0e1b62004-07-07 20:54:48 +0000152 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000153 ... '''Backslashes in a raw docstring: m\\n'''
154 >>> print f.__doc__
155 Backslashes in a raw docstring: m\n
Tim Peters4e0e1b62004-07-07 20:54:48 +0000156
Tim Peters8a7d2d52001-01-16 07:10:57 +0000157The starting column doesn't matter:
158
159>>> assert "Easy!"
160 >>> import math
161 >>> math.floor(1.9)
162 1.0
163
164and as many leading whitespace characters are stripped from the expected
165output as appeared in the initial ">>>" line that triggered it.
166
167If you execute this very file, the examples above will be found and
Tim Peters80e53142004-08-09 04:34:45 +0000168executed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000169"""
Edward Loper8e4a34b2004-08-12 02:34:27 +0000170__docformat__ = 'reStructuredText en'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000171
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000172__all__ = [
Edward Loperb7503ff2004-08-19 19:19:03 +0000173 # 0, Option Flags
174 'register_optionflag',
175 'DONT_ACCEPT_TRUE_FOR_1',
176 'DONT_ACCEPT_BLANKLINE',
177 'NORMALIZE_WHITESPACE',
178 'ELLIPSIS',
179 'UNIFIED_DIFF',
180 'CONTEXT_DIFF',
Tim Petersc6cbab02004-08-22 19:43:28 +0000181 'NDIFF_DIFF',
Edward Loperb7503ff2004-08-19 19:19:03 +0000182 # 1. Utility Functions
Tim Peters8485b562004-08-04 18:46:34 +0000183 'is_private',
Edward Loperb7503ff2004-08-19 19:19:03 +0000184 # 2. Example & DocTest
Tim Peters8485b562004-08-04 18:46:34 +0000185 'Example',
186 'DocTest',
Edward Loperb7503ff2004-08-19 19:19:03 +0000187 # 3. Doctest Parser
188 'DocTestParser',
189 # 4. Doctest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000190 'DocTestFinder',
Edward Loperb7503ff2004-08-19 19:19:03 +0000191 # 5. Doctest Runner
Tim Peters8485b562004-08-04 18:46:34 +0000192 'DocTestRunner',
Edward Loperb7503ff2004-08-19 19:19:03 +0000193 'OutputChecker',
194 'DocTestFailure',
195 'UnexpectedException',
196 'DebugRunner',
197 # 6. Test Functions
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000198 'testmod',
199 'run_docstring_examples',
Edward Loperb7503ff2004-08-19 19:19:03 +0000200 # 7. Tester
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000201 'Tester',
Edward Loperb7503ff2004-08-19 19:19:03 +0000202 # 8. Unittest Support
Tim Peters19397e52004-08-06 22:02:59 +0000203 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000204 'DocTestSuite',
Edward Loperb7503ff2004-08-19 19:19:03 +0000205 'DocFileCase',
206 'DocFileTest',
207 'DocFileSuite',
208 # 9. Debugging Support
209 'script_from_examples',
Tim Petersdb3756d2003-06-29 05:30:48 +0000210 'testsource',
Edward Loperb7503ff2004-08-19 19:19:03 +0000211 'debug_src',
212 'debug_script',
Tim Petersdb3756d2003-06-29 05:30:48 +0000213 'debug',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000214]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000215
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000216import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000217
Tim Peters19397e52004-08-06 22:02:59 +0000218import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000219import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000220import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000221from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000222
Tim Petersdd50cb72004-08-23 22:42:55 +0000223# Don't whine about the deprecated is_private function in this
224# module's tests.
225warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
226 __name__, 0)
227
Jim Fulton356fd192004-08-09 11:34:47 +0000228real_pdb_set_trace = pdb.set_trace
229
Tim Peters19397e52004-08-06 22:02:59 +0000230# There are 4 basic classes:
231# - Example: a <source, want> pair, plus an intra-docstring line number.
232# - DocTest: a collection of examples, parsed from a docstring, plus
233# info about where the docstring came from (name, filename, lineno).
234# - DocTestFinder: extracts DocTests from a given object's docstring and
235# its contained objects' docstrings.
236# - DocTestRunner: runs DocTest cases, and accumulates statistics.
237#
238# So the basic picture is:
239#
240# list of:
241# +------+ +---------+ +-------+
242# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
243# +------+ +---------+ +-------+
244# | Example |
245# | ... |
246# | Example |
247# +---------+
248
Edward Loperac20f572004-08-12 02:02:24 +0000249# Option constants.
250OPTIONFLAGS_BY_NAME = {}
251def register_optionflag(name):
252 flag = 1 << len(OPTIONFLAGS_BY_NAME)
253 OPTIONFLAGS_BY_NAME[name] = flag
254 return flag
255
256DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
257DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
258NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
259ELLIPSIS = register_optionflag('ELLIPSIS')
260UNIFIED_DIFF = register_optionflag('UNIFIED_DIFF')
261CONTEXT_DIFF = register_optionflag('CONTEXT_DIFF')
Tim Petersc6cbab02004-08-22 19:43:28 +0000262NDIFF_DIFF = register_optionflag('NDIFF_DIFF')
Edward Loperac20f572004-08-12 02:02:24 +0000263
264# Special string markers for use in `want` strings:
265BLANKLINE_MARKER = '<BLANKLINE>'
266ELLIPSIS_MARKER = '...'
267
Tim Peters8485b562004-08-04 18:46:34 +0000268######################################################################
269## Table of Contents
270######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000271# 1. Utility Functions
272# 2. Example & DocTest -- store test cases
273# 3. DocTest Parser -- extracts examples from strings
274# 4. DocTest Finder -- extracts test cases from objects
275# 5. DocTest Runner -- runs test cases
276# 6. Test Functions -- convenient wrappers for testing
277# 7. Tester Class -- for backwards compatibility
278# 8. Unittest Support
279# 9. Debugging Support
280# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000281
Tim Peters8485b562004-08-04 18:46:34 +0000282######################################################################
283## 1. Utility Functions
284######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000285
286def is_private(prefix, base):
287 """prefix, base -> true iff name prefix + "." + base is "private".
288
289 Prefix may be an empty string, and base does not contain a period.
290 Prefix is ignored (although functions you write conforming to this
291 protocol may make use of it).
292 Return true iff base begins with an (at least one) underscore, but
293 does not both begin and end with (at least) two underscores.
294
295 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000296 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000297 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000298 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000299 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000300 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000301 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000302 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000303 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000304 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000305 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000306 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000307 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000308 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000309 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000310 warnings.warn("is_private is deprecated; it wasn't useful; "
311 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000312 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000313 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
314
Tim Peters8485b562004-08-04 18:46:34 +0000315def _extract_future_flags(globs):
316 """
317 Return the compiler-flags associated with the future features that
318 have been imported into the given namespace (globs).
319 """
320 flags = 0
321 for fname in __future__.all_feature_names:
322 feature = globs.get(fname, None)
323 if feature is getattr(__future__, fname):
324 flags |= feature.compiler_flag
325 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000326
Tim Peters8485b562004-08-04 18:46:34 +0000327def _normalize_module(module, depth=2):
328 """
329 Return the module specified by `module`. In particular:
330 - If `module` is a module, then return module.
331 - If `module` is a string, then import and return the
332 module with that name.
333 - If `module` is None, then return the calling module.
334 The calling module is assumed to be the module of
335 the stack frame at the given depth in the call stack.
336 """
337 if inspect.ismodule(module):
338 return module
339 elif isinstance(module, (str, unicode)):
340 return __import__(module, globals(), locals(), ["*"])
341 elif module is None:
342 return sys.modules[sys._getframe(depth).f_globals['__name__']]
343 else:
344 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000345
Edward Lopera1ef6112004-08-09 16:14:41 +0000346def _tag_msg(tag, msg, indent=' '):
Tim Peters8485b562004-08-04 18:46:34 +0000347 """
348 Return a string that displays a tag-and-message pair nicely,
349 keeping the tag and its message on the same line when that
Edward Lopera1ef6112004-08-09 16:14:41 +0000350 makes sense. If the message is displayed on separate lines,
351 then `indent` is added to the beginning of each line.
Tim Peters8485b562004-08-04 18:46:34 +0000352 """
Tim Peters8485b562004-08-04 18:46:34 +0000353 # If the message doesn't end in a newline, then add one.
354 if msg[-1:] != '\n':
355 msg += '\n'
356 # If the message is short enough, and contains no internal
357 # newlines, then display it on the same line as the tag.
358 # Otherwise, display the tag on its own line.
359 if (len(tag) + len(msg) < 75 and
360 msg.find('\n', 0, len(msg)-1) == -1):
361 return '%s: %s' % (tag, msg)
362 else:
Edward Lopera1ef6112004-08-09 16:14:41 +0000363 msg = '\n'.join([indent+l for l in msg[:-1].split('\n')])
364 return '%s:\n%s\n' % (tag, msg)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000365
Edward Loper8e4a34b2004-08-12 02:34:27 +0000366def _exception_traceback(exc_info):
367 """
368 Return a string containing a traceback message for the given
369 exc_info tuple (as returned by sys.exc_info()).
370 """
371 # Get a traceback message.
372 excout = StringIO()
373 exc_type, exc_val, exc_tb = exc_info
374 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
375 return excout.getvalue()
376
Tim Peters8485b562004-08-04 18:46:34 +0000377# Override some StringIO methods.
378class _SpoofOut(StringIO):
379 def getvalue(self):
380 result = StringIO.getvalue(self)
381 # If anything at all was written, make sure there's a trailing
382 # newline. There's no way for the expected output to indicate
383 # that a trailing newline is missing.
384 if result and not result.endswith("\n"):
385 result += "\n"
386 # Prevent softspace from screwing up the next test case, in
387 # case they used print with a trailing comma in an example.
388 if hasattr(self, "softspace"):
389 del self.softspace
390 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000391
Tim Peters8485b562004-08-04 18:46:34 +0000392 def truncate(self, size=None):
393 StringIO.truncate(self, size)
394 if hasattr(self, "softspace"):
395 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000396
Tim Peters26b3ebb2004-08-19 08:10:08 +0000397# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000398def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000399 """
400 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000401 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000402 False
403 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000404 if ELLIPSIS_MARKER not in want:
405 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000406
Tim Peters26b3ebb2004-08-19 08:10:08 +0000407 # Find "the real" strings.
408 ws = want.split(ELLIPSIS_MARKER)
409 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000410
Tim Petersdc5de3b2004-08-19 14:06:20 +0000411 # Deal with exact matches possibly needed at one or both ends.
412 startpos, endpos = 0, len(got)
413 w = ws[0]
414 if w: # starts with exact match
415 if got.startswith(w):
416 startpos = len(w)
417 del ws[0]
418 else:
419 return False
420 w = ws[-1]
421 if w: # ends with exact match
422 if got.endswith(w):
423 endpos -= len(w)
424 del ws[-1]
425 else:
426 return False
427
428 if startpos > endpos:
429 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000430 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000431 return False
432
433 # For the rest, we only need to find the leftmost non-overlapping
434 # match for each piece. If there's no overall match that way alone,
435 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000436 for w in ws:
437 # w may be '' at times, if there are consecutive ellipses, or
438 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000439 # Search for an empty string succeeds, and doesn't change startpos.
440 startpos = got.find(w, startpos, endpos)
441 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000442 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000443 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000444
Tim Petersdc5de3b2004-08-19 14:06:20 +0000445 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000446
Tim Peters8485b562004-08-04 18:46:34 +0000447######################################################################
448## 2. Example & DocTest
449######################################################################
450## - An "example" is a <source, want> pair, where "source" is a
451## fragment of source code, and "want" is the expected output for
452## "source." The Example class also includes information about
453## where the example was extracted from.
454##
Edward Lopera1ef6112004-08-09 16:14:41 +0000455## - A "doctest" is a collection of examples, typically extracted from
456## a string (such as an object's docstring). The DocTest class also
457## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000458
Tim Peters8485b562004-08-04 18:46:34 +0000459class Example:
460 """
461 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000462 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000463
Edward Loper74bca7a2004-08-12 02:27:44 +0000464 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000465 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000466
Edward Loper74bca7a2004-08-12 02:27:44 +0000467 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000468 from stdout, or a traceback in case of exception). `want` ends
469 with a newline unless it's empty, in which case it's an empty
470 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000471
Edward Loper74bca7a2004-08-12 02:27:44 +0000472 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000473 this Example where the Example begins. This line number is
474 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000475
476 - indent: The example's indentation in the DocTest string.
477 I.e., the number of space characters that preceed the
478 example's first prompt.
479
480 - options: A dictionary mapping from option flags to True or
481 False, which is used to override default options for this
482 example. Any option flags not contained in this dictionary
483 are left at their default value (as specified by the
484 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000485 """
Edward Loper74bca7a2004-08-12 02:27:44 +0000486 def __init__(self, source, want, lineno, indent=0, options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000487 # Normalize inputs.
488 if not source.endswith('\n'):
489 source += '\n'
490 if want and not want.endswith('\n'):
491 want += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000492 # Store properties.
493 self.source = source
494 self.want = want
495 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000496 self.indent = indent
497 if options is None: options = {}
498 self.options = options
Tim Peters8a7d2d52001-01-16 07:10:57 +0000499
Tim Peters8485b562004-08-04 18:46:34 +0000500class DocTest:
501 """
502 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000503 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000504
Tim Peters8485b562004-08-04 18:46:34 +0000505 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000506
Tim Peters8485b562004-08-04 18:46:34 +0000507 - globs: The namespace (aka globals) that the examples should
508 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000509
Tim Peters8485b562004-08-04 18:46:34 +0000510 - name: A name identifying the DocTest (typically, the name of
511 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000512
Tim Peters8485b562004-08-04 18:46:34 +0000513 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000514 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000515
Tim Peters8485b562004-08-04 18:46:34 +0000516 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000517 begins, or `None` if the line number is unavailable. This
518 line number is zero-based, with respect to the beginning of
519 the file.
520
521 - docstring: The string that the examples were extracted from,
522 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000523 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000524 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000525 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000526 Create a new DocTest containing the given examples. The
527 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000528 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000529 assert not isinstance(examples, basestring), \
530 "DocTest no longer accepts str; use DocTestParser instead"
531 self.examples = examples
532 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000533 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000534 self.name = name
535 self.filename = filename
536 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000537
538 def __repr__(self):
539 if len(self.examples) == 0:
540 examples = 'no examples'
541 elif len(self.examples) == 1:
542 examples = '1 example'
543 else:
544 examples = '%d examples' % len(self.examples)
545 return ('<DocTest %s from %s:%s (%s)>' %
546 (self.name, self.filename, self.lineno, examples))
547
548
549 # This lets us sort tests by name:
550 def __cmp__(self, other):
551 if not isinstance(other, DocTest):
552 return -1
553 return cmp((self.name, self.filename, self.lineno, id(self)),
554 (other.name, other.filename, other.lineno, id(other)))
555
556######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000557## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000558######################################################################
559
Edward Lopera1ef6112004-08-09 16:14:41 +0000560class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000561 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000562 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000563 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000564 # This regular expression is used to find doctest examples in a
565 # string. It defines three groups: `source` is the source code
566 # (including leading indentation and prompts); `indent` is the
567 # indentation of the first (PS1) line of the source code; and
568 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000569 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000570 # Source consists of a PS1 line followed by zero or more PS2 lines.
571 (?P<source>
572 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
573 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
574 \n?
575 # Want consists of any non-blank lines that do not start with PS1.
576 (?P<want> (?:(?![ ]*$) # Not a blank line
577 (?![ ]*>>>) # Not a line starting with PS1
578 .*$\n? # But any other line
579 )*)
580 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000581
Tim Peters7ea48dd2004-08-13 01:52:59 +0000582 # A callable returning a true value iff its argument is a blank line
583 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000584 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000585
Edward Lopera1ef6112004-08-09 16:14:41 +0000586 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000587 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000588 Extract all doctest examples from the given string, and
589 collect them into a `DocTest` object.
590
591 `globs`, `name`, `filename`, and `lineno` are attributes for
592 the new `DocTest` object. See the documentation for `DocTest`
593 for more information.
594 """
595 return DocTest(self.get_examples(string, name), globs,
596 name, filename, lineno, string)
597
598 def get_examples(self, string, name='<string>'):
599 """
600 Extract all doctest examples from the given string, and return
601 them as a list of `Example` objects. Line numbers are
602 0-based, because it's most common in doctests that nothing
603 interesting appears on the same line as opening triple-quote,
604 and so the first interesting line is called \"line 1\" then.
605
606 The optional argument `name` is a name identifying this
607 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000608
609 >>> text = '''
610 ... >>> x, y = 2, 3 # no output expected
611 ... >>> if 1:
612 ... ... print x
613 ... ... print y
614 ... 2
615 ... 3
616 ...
617 ... Some text.
618 ... >>> x+y
619 ... 5
620 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000621 >>> for x in DocTestParser().get_examples(text):
Edward Loper78b58f32004-08-09 02:56:02 +0000622 ... print (x.source, x.want, x.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000623 ('x, y = 2, 3 # no output expected\\n', '', 1)
Edward Loper7c748462004-08-09 02:06:06 +0000624 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
Tim Petersbb431472004-08-09 03:51:46 +0000625 ('x+y\\n', '5\\n', 9)
Edward Loper7c748462004-08-09 02:06:06 +0000626 """
627 examples = []
628 charno, lineno = 0, 0
629 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000630 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000631 # Update lineno (lines before this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000632 lineno += string.count('\n', charno, m.start())
Edward Loper7c748462004-08-09 02:06:06 +0000633 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000634 (source, want) = self._parse_example(m, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000635 # Extract extra options from the source.
636 options = self._find_options(source, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000637 # Create an Example, and add it to the list.
Edward Loperb51b2342004-08-17 16:37:12 +0000638 if not self._IS_BLANK_OR_COMMENT(source):
639 examples.append( Example(source, want, lineno,
640 len(m.group('indent')), options) )
Edward Loper7c748462004-08-09 02:06:06 +0000641 # Update lineno (lines inside this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000642 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000643 # Update charno.
644 charno = m.end()
645 return examples
646
Edward Lopera1ef6112004-08-09 16:14:41 +0000647 def get_program(self, string, name="<string>"):
Edward Loper7c748462004-08-09 02:06:06 +0000648 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000649 Return an executable program from the given string, as a string.
Edward Loper7c748462004-08-09 02:06:06 +0000650
651 The format of this isn't rigidly defined. In general, doctest
652 examples become the executable statements in the result, and
653 their expected outputs become comments, preceded by an \"#Expected:\"
654 comment. Everything else (text, comments, everything not part of
655 a doctest test) is also placed in comments.
656
Edward Lopera1ef6112004-08-09 16:14:41 +0000657 The optional argument `name` is a name identifying this
658 string, and is only used for error messages.
659
Edward Loper7c748462004-08-09 02:06:06 +0000660 >>> text = '''
661 ... >>> x, y = 2, 3 # no output expected
662 ... >>> if 1:
663 ... ... print x
664 ... ... print y
665 ... 2
666 ... 3
667 ...
668 ... Some text.
669 ... >>> x+y
670 ... 5
671 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000672 >>> print DocTestParser().get_program(text)
Edward Loper7c748462004-08-09 02:06:06 +0000673 x, y = 2, 3 # no output expected
674 if 1:
675 print x
676 print y
677 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000678 ## 2
679 ## 3
Edward Loper7c748462004-08-09 02:06:06 +0000680 #
Edward Lopera5db6002004-08-12 02:41:30 +0000681 # Some text.
Edward Loper7c748462004-08-09 02:06:06 +0000682 x+y
683 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000684 ## 5
Edward Loper7c748462004-08-09 02:06:06 +0000685 """
Edward Lopera5db6002004-08-12 02:41:30 +0000686 string = string.expandtabs()
687 # If all lines begin with the same indentation, then strip it.
688 min_indent = self._min_indent(string)
689 if min_indent > 0:
690 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
691
Edward Loper7c748462004-08-09 02:06:06 +0000692 output = []
693 charnum, lineno = 0, 0
694 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000695 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000696 # Add any text before this example, as a comment.
697 if m.start() > charnum:
Edward Lopera1ef6112004-08-09 16:14:41 +0000698 lines = string[charnum:m.start()-1].split('\n')
Edward Loper7c748462004-08-09 02:06:06 +0000699 output.extend([self._comment_line(l) for l in lines])
700 lineno += len(lines)
701
702 # Extract source/want from the regexp match.
Edward Loper74bca7a2004-08-12 02:27:44 +0000703 (source, want) = self._parse_example(m, name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000704 # Display the source
705 output.append(source)
706 # Display the expected output, if any
707 if want:
708 output.append('# Expected:')
Edward Lopera5db6002004-08-12 02:41:30 +0000709 output.extend(['## '+l for l in want.split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000710
711 # Update the line number & char number.
Edward Lopera1ef6112004-08-09 16:14:41 +0000712 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000713 charnum = m.end()
714 # Add any remaining text, as comments.
715 output.extend([self._comment_line(l)
Edward Lopera1ef6112004-08-09 16:14:41 +0000716 for l in string[charnum:].split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000717 # Trim junk on both ends.
718 while output and output[-1] == '#':
719 output.pop()
720 while output and output[0] == '#':
721 output.pop(0)
722 # Combine the output, and return it.
723 return '\n'.join(output)
724
Edward Loper74bca7a2004-08-12 02:27:44 +0000725 def _parse_example(self, m, name, lineno):
726 """
727 Given a regular expression match from `_EXAMPLE_RE` (`m`),
728 return a pair `(source, want)`, where `source` is the matched
729 example's source code (with prompts and indentation stripped);
730 and `want` is the example's expected output (with indentation
731 stripped).
732
733 `name` is the string's name, and `lineno` is the line number
734 where the example starts; both are used for error messages.
735 """
Edward Loper7c748462004-08-09 02:06:06 +0000736 # Get the example's indentation level.
737 indent = len(m.group('indent'))
738
739 # Divide source into lines; check that they're properly
740 # indented; and then strip their indentation & prompts.
741 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000742 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000743 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000744 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000745
Tim Petersc5049152004-08-22 17:34:58 +0000746 # Divide want into lines; check that it's properly indented; and
747 # then strip the indentation. Spaces before the last newline should
748 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000749 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000750 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000751 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
752 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000753 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000754 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000755 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000756
757 return source, want
758
Edward Loper74bca7a2004-08-12 02:27:44 +0000759 # This regular expression looks for option directives in the
760 # source code of an example. Option directives are comments
761 # starting with "doctest:". Warning: this may give false
762 # positives for string-literals that contain the string
763 # "#doctest:". Eliminating these false positives would require
764 # actually parsing the string; but we limit them by ignoring any
765 # line containing "#doctest:" that is *followed* by a quote mark.
766 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
767 re.MULTILINE)
768
769 def _find_options(self, source, name, lineno):
770 """
771 Return a dictionary containing option overrides extracted from
772 option directives in the given source string.
773
774 `name` is the string's name, and `lineno` is the line number
775 where the example starts; both are used for error messages.
776 """
777 options = {}
778 # (note: with the current regexp, this will match at most once:)
779 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
780 option_strings = m.group(1).replace(',', ' ').split()
781 for option in option_strings:
782 if (option[0] not in '+-' or
783 option[1:] not in OPTIONFLAGS_BY_NAME):
784 raise ValueError('line %r of the doctest for %s '
785 'has an invalid option: %r' %
786 (lineno+1, name, option))
787 flag = OPTIONFLAGS_BY_NAME[option[1:]]
788 options[flag] = (option[0] == '+')
789 if options and self._IS_BLANK_OR_COMMENT(source):
790 raise ValueError('line %r of the doctest for %s has an option '
791 'directive on a line with no example: %r' %
792 (lineno, name, source))
793 return options
794
Edward Lopera5db6002004-08-12 02:41:30 +0000795 # This regular expression finds the indentation of every non-blank
796 # line in a string.
797 _INDENT_RE = re.compile('^([ ]+)(?=\S)', re.MULTILINE)
798
799 def _min_indent(self, s):
800 "Return the minimum indentation of any non-blank line in `s`"
801 return min([len(indent) for indent in self._INDENT_RE.findall(s)])
802
Edward Loper7c748462004-08-09 02:06:06 +0000803 def _comment_line(self, line):
Edward Loper74bca7a2004-08-12 02:27:44 +0000804 "Return a commented form of the given line"
Edward Loper7c748462004-08-09 02:06:06 +0000805 line = line.rstrip()
Tim Petersdd0e4752004-08-09 03:31:56 +0000806 if line:
Edward Lopera5db6002004-08-12 02:41:30 +0000807 return '# '+line
Tim Petersdd0e4752004-08-09 03:31:56 +0000808 else:
809 return '#'
Edward Loper7c748462004-08-09 02:06:06 +0000810
Edward Lopera1ef6112004-08-09 16:14:41 +0000811 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000812 """
813 Given the lines of a source string (including prompts and
814 leading indentation), check to make sure that every prompt is
815 followed by a space character. If any line is not followed by
816 a space character, then raise ValueError.
817 """
Edward Loper7c748462004-08-09 02:06:06 +0000818 for i, line in enumerate(lines):
819 if len(line) >= indent+4 and line[indent+3] != ' ':
820 raise ValueError('line %r of the docstring for %s '
821 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000822 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000823 line[indent:indent+3], line))
824
Edward Lopera1ef6112004-08-09 16:14:41 +0000825 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000826 """
827 Check that every line in the given list starts with the given
828 prefix; if any line does not, then raise a ValueError.
829 """
Edward Loper7c748462004-08-09 02:06:06 +0000830 for i, line in enumerate(lines):
831 if line and not line.startswith(prefix):
832 raise ValueError('line %r of the docstring for %s has '
833 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000834 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000835
836
837######################################################################
838## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000839######################################################################
840
841class DocTestFinder:
842 """
843 A class used to extract the DocTests that are relevant to a given
844 object, from its docstring and the docstrings of its contained
845 objects. Doctests can currently be extracted from the following
846 object types: modules, functions, classes, methods, staticmethods,
847 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000848 """
849
Edward Lopera1ef6112004-08-09 16:14:41 +0000850 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000851 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000852 """
853 Create a new doctest finder.
854
Edward Lopera1ef6112004-08-09 16:14:41 +0000855 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000856 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000857 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000858 signature for this factory function should match the signature
859 of the DocTest constructor.
860
Tim Peters8485b562004-08-04 18:46:34 +0000861 If the optional argument `recurse` is false, then `find` will
862 only examine the given object, and not any contained objects.
863 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000864 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000865 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000866 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000867 # _namefilter is undocumented, and exists only for temporary backward-
868 # compatibility support of testmod's deprecated isprivate mess.
869 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000870
871 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000872 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000873 """
874 Return a list of the DocTests that are defined by the given
875 object's docstring, or by any of its contained objects'
876 docstrings.
877
878 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000879 the given object. If the module is not specified or is None, then
880 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000881 correct module. The object's module is used:
882
883 - As a default namespace, if `globs` is not specified.
884 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000885 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000886 - To find the name of the file containing the object.
887 - To help find the line number of the object within its
888 file.
889
Tim Petersf3f57472004-08-08 06:11:48 +0000890 Contained objects whose module does not match `module` are ignored.
891
892 If `module` is False, no attempt to find the module will be made.
893 This is obscure, of use mostly in tests: if `module` is False, or
894 is None but cannot be found automatically, then all objects are
895 considered to belong to the (non-existent) module, so all contained
896 objects will (recursively) be searched for doctests.
897
Tim Peters8485b562004-08-04 18:46:34 +0000898 The globals for each DocTest is formed by combining `globs`
899 and `extraglobs` (bindings in `extraglobs` override bindings
900 in `globs`). A new copy of the globals dictionary is created
901 for each DocTest. If `globs` is not specified, then it
902 defaults to the module's `__dict__`, if specified, or {}
903 otherwise. If `extraglobs` is not specified, then it defaults
904 to {}.
905
Tim Peters8485b562004-08-04 18:46:34 +0000906 """
907 # If name was not specified, then extract it from the object.
908 if name is None:
909 name = getattr(obj, '__name__', None)
910 if name is None:
911 raise ValueError("DocTestFinder.find: name must be given "
912 "when obj.__name__ doesn't exist: %r" %
913 (type(obj),))
914
915 # Find the module that contains the given object (if obj is
916 # a module, then module=obj.). Note: this may fail, in which
917 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000918 if module is False:
919 module = None
920 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000921 module = inspect.getmodule(obj)
922
923 # Read the module's source code. This is used by
924 # DocTestFinder._find_lineno to find the line number for a
925 # given object's docstring.
926 try:
927 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
928 source_lines = linecache.getlines(file)
929 if not source_lines:
930 source_lines = None
931 except TypeError:
932 source_lines = None
933
934 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000935 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000936 if module is None:
937 globs = {}
938 else:
939 globs = module.__dict__.copy()
940 else:
941 globs = globs.copy()
942 if extraglobs is not None:
943 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000944
Tim Peters8485b562004-08-04 18:46:34 +0000945 # Recursively expore `obj`, extracting DocTests.
946 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000947 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000948 return tests
949
950 def _filter(self, obj, prefix, base):
951 """
952 Return true if the given object should not be examined.
953 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000954 return (self._namefilter is not None and
955 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000956
957 def _from_module(self, module, object):
958 """
959 Return true if the given object is defined in the given
960 module.
961 """
962 if module is None:
963 return True
964 elif inspect.isfunction(object):
965 return module.__dict__ is object.func_globals
966 elif inspect.isclass(object):
967 return module.__name__ == object.__module__
968 elif inspect.getmodule(object) is not None:
969 return module is inspect.getmodule(object)
970 elif hasattr(object, '__module__'):
971 return module.__name__ == object.__module__
972 elif isinstance(object, property):
973 return True # [XX] no way not be sure.
974 else:
975 raise ValueError("object must be a class or function")
976
Tim Petersf3f57472004-08-08 06:11:48 +0000977 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000978 """
979 Find tests for the given object and any contained objects, and
980 add them to `tests`.
981 """
982 if self._verbose:
983 print 'Finding tests in %s' % name
984
985 # If we've already processed this object, then ignore it.
986 if id(obj) in seen:
987 return
988 seen[id(obj)] = 1
989
990 # Find a test for this object, and add it to the list of tests.
991 test = self._get_test(obj, name, module, globs, source_lines)
992 if test is not None:
993 tests.append(test)
994
995 # Look for tests in a module's contained objects.
996 if inspect.ismodule(obj) and self._recurse:
997 for valname, val in obj.__dict__.items():
998 # Check if this contained object should be ignored.
999 if self._filter(val, name, valname):
1000 continue
1001 valname = '%s.%s' % (name, valname)
1002 # Recurse to functions & classes.
1003 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +00001004 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001005 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001006 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001007
1008 # Look for tests in a module's __test__ dictionary.
1009 if inspect.ismodule(obj) and self._recurse:
1010 for valname, val in getattr(obj, '__test__', {}).items():
1011 if not isinstance(valname, basestring):
1012 raise ValueError("DocTestFinder.find: __test__ keys "
1013 "must be strings: %r" %
1014 (type(valname),))
1015 if not (inspect.isfunction(val) or inspect.isclass(val) or
1016 inspect.ismethod(val) or inspect.ismodule(val) or
1017 isinstance(val, basestring)):
1018 raise ValueError("DocTestFinder.find: __test__ values "
1019 "must be strings, functions, methods, "
1020 "classes, or modules: %r" %
1021 (type(val),))
1022 valname = '%s.%s' % (name, valname)
1023 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001024 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001025
1026 # Look for tests in a class's contained objects.
1027 if inspect.isclass(obj) and self._recurse:
1028 for valname, val in obj.__dict__.items():
1029 # Check if this contained object should be ignored.
1030 if self._filter(val, name, valname):
1031 continue
1032 # Special handling for staticmethod/classmethod.
1033 if isinstance(val, staticmethod):
1034 val = getattr(obj, valname)
1035 if isinstance(val, classmethod):
1036 val = getattr(obj, valname).im_func
1037
1038 # Recurse to methods, properties, and nested classes.
1039 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001040 isinstance(val, property)) and
1041 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001042 valname = '%s.%s' % (name, valname)
1043 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001044 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001045
1046 def _get_test(self, obj, name, module, globs, source_lines):
1047 """
1048 Return a DocTest for the given object, if it defines a docstring;
1049 otherwise, return None.
1050 """
1051 # Extract the object's docstring. If it doesn't have one,
1052 # then return None (no test for this object).
1053 if isinstance(obj, basestring):
1054 docstring = obj
1055 else:
1056 try:
1057 if obj.__doc__ is None:
1058 return None
1059 docstring = str(obj.__doc__)
1060 except (TypeError, AttributeError):
1061 return None
1062
1063 # Don't bother if the docstring is empty.
1064 if not docstring:
1065 return None
1066
1067 # Find the docstring's location in the file.
1068 lineno = self._find_lineno(obj, source_lines)
1069
1070 # Return a DocTest for this object.
1071 if module is None:
1072 filename = None
1073 else:
1074 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001075 if filename[-4:] in (".pyc", ".pyo"):
1076 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001077 return self._parser.get_doctest(docstring, globs, name,
1078 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001079
1080 def _find_lineno(self, obj, source_lines):
1081 """
1082 Return a line number of the given object's docstring. Note:
1083 this method assumes that the object has a docstring.
1084 """
1085 lineno = None
1086
1087 # Find the line number for modules.
1088 if inspect.ismodule(obj):
1089 lineno = 0
1090
1091 # Find the line number for classes.
1092 # Note: this could be fooled if a class is defined multiple
1093 # times in a single file.
1094 if inspect.isclass(obj):
1095 if source_lines is None:
1096 return None
1097 pat = re.compile(r'^\s*class\s*%s\b' %
1098 getattr(obj, '__name__', '-'))
1099 for i, line in enumerate(source_lines):
1100 if pat.match(line):
1101 lineno = i
1102 break
1103
1104 # Find the line number for functions & methods.
1105 if inspect.ismethod(obj): obj = obj.im_func
1106 if inspect.isfunction(obj): obj = obj.func_code
1107 if inspect.istraceback(obj): obj = obj.tb_frame
1108 if inspect.isframe(obj): obj = obj.f_code
1109 if inspect.iscode(obj):
1110 lineno = getattr(obj, 'co_firstlineno', None)-1
1111
1112 # Find the line number where the docstring starts. Assume
1113 # that it's the first line that begins with a quote mark.
1114 # Note: this could be fooled by a multiline function
1115 # signature, where a continuation line begins with a quote
1116 # mark.
1117 if lineno is not None:
1118 if source_lines is None:
1119 return lineno+1
1120 pat = re.compile('(^|.*:)\s*\w*("|\')')
1121 for lineno in range(lineno, len(source_lines)):
1122 if pat.match(source_lines[lineno]):
1123 return lineno
1124
1125 # We couldn't find the line number.
1126 return None
1127
1128######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001129## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001130######################################################################
1131
Tim Peters8485b562004-08-04 18:46:34 +00001132class DocTestRunner:
1133 """
1134 A class used to run DocTest test cases, and accumulate statistics.
1135 The `run` method is used to process a single DocTest case. It
1136 returns a tuple `(f, t)`, where `t` is the number of test cases
1137 tried, and `f` is the number of test cases that failed.
1138
1139 >>> tests = DocTestFinder().find(_TestClass)
1140 >>> runner = DocTestRunner(verbose=False)
1141 >>> for test in tests:
1142 ... print runner.run(test)
1143 (0, 2)
1144 (0, 1)
1145 (0, 2)
1146 (0, 2)
1147
1148 The `summarize` method prints a summary of all the test cases that
1149 have been run by the runner, and returns an aggregated `(f, t)`
1150 tuple:
1151
1152 >>> runner.summarize(verbose=1)
1153 4 items passed all tests:
1154 2 tests in _TestClass
1155 2 tests in _TestClass.__init__
1156 2 tests in _TestClass.get
1157 1 tests in _TestClass.square
1158 7 tests in 4 items.
1159 7 passed and 0 failed.
1160 Test passed.
1161 (0, 7)
1162
1163 The aggregated number of tried examples and failed examples is
1164 also available via the `tries` and `failures` attributes:
1165
1166 >>> runner.tries
1167 7
1168 >>> runner.failures
1169 0
1170
1171 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001172 by an `OutputChecker`. This comparison may be customized with a
1173 number of option flags; see the documentation for `testmod` for
1174 more information. If the option flags are insufficient, then the
1175 comparison may also be customized by passing a subclass of
1176 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001177
1178 The test runner's display output can be controlled in two ways.
1179 First, an output function (`out) can be passed to
1180 `TestRunner.run`; this function will be called with strings that
1181 should be displayed. It defaults to `sys.stdout.write`. If
1182 capturing the output is not sufficient, then the display output
1183 can be also customized by subclassing DocTestRunner, and
1184 overriding the methods `report_start`, `report_success`,
1185 `report_unexpected_exception`, and `report_failure`.
1186 """
1187 # This divider string is used to separate failure messages, and to
1188 # separate sections of the summary.
1189 DIVIDER = "*" * 70
1190
Edward Loper34fcb142004-08-09 02:45:41 +00001191 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001192 """
1193 Create a new test runner.
1194
Edward Loper34fcb142004-08-09 02:45:41 +00001195 Optional keyword arg `checker` is the `OutputChecker` that
1196 should be used to compare the expected outputs and actual
1197 outputs of doctest examples.
1198
Tim Peters8485b562004-08-04 18:46:34 +00001199 Optional keyword arg 'verbose' prints lots of stuff if true,
1200 only failures if false; by default, it's true iff '-v' is in
1201 sys.argv.
1202
1203 Optional argument `optionflags` can be used to control how the
1204 test runner compares expected output to actual output, and how
1205 it displays failures. See the documentation for `testmod` for
1206 more information.
1207 """
Edward Loper34fcb142004-08-09 02:45:41 +00001208 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001209 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001210 verbose = '-v' in sys.argv
1211 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001212 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001213 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001214
Tim Peters8485b562004-08-04 18:46:34 +00001215 # Keep track of the examples we've run.
1216 self.tries = 0
1217 self.failures = 0
1218 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001219
Tim Peters8485b562004-08-04 18:46:34 +00001220 # Create a fake output target for capturing doctest output.
1221 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001222
Tim Peters8485b562004-08-04 18:46:34 +00001223 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001224 # Reporting methods
1225 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001226
Tim Peters8485b562004-08-04 18:46:34 +00001227 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001228 """
Tim Peters8485b562004-08-04 18:46:34 +00001229 Report that the test runner is about to process the given
1230 example. (Only displays a message if verbose=True)
1231 """
1232 if self._verbose:
1233 out(_tag_msg("Trying", example.source) +
1234 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001235
Tim Peters8485b562004-08-04 18:46:34 +00001236 def report_success(self, out, test, example, got):
1237 """
1238 Report that the given example ran successfully. (Only
1239 displays a message if verbose=True)
1240 """
1241 if self._verbose:
1242 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001243
Tim Peters8485b562004-08-04 18:46:34 +00001244 def report_failure(self, out, test, example, got):
1245 """
1246 Report that the given example failed.
1247 """
1248 # Print an error message.
Edward Loper8e4a34b2004-08-12 02:34:27 +00001249 out(self._failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001250 self._checker.output_difference(example.want, got,
1251 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001252
Tim Peters8485b562004-08-04 18:46:34 +00001253 def report_unexpected_exception(self, out, test, example, exc_info):
1254 """
1255 Report that the given example raised an unexpected exception.
1256 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001257 out(self._failure_header(test, example) +
1258 _tag_msg("Exception raised", _exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001259
Edward Loper8e4a34b2004-08-12 02:34:27 +00001260 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001261 out = [self.DIVIDER]
1262 if test.filename:
1263 if test.lineno is not None and example.lineno is not None:
1264 lineno = test.lineno + example.lineno + 1
1265 else:
1266 lineno = '?'
1267 out.append('File "%s", line %s, in %s' %
1268 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001269 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001270 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1271 out.append('Failed example:')
1272 source = example.source
1273 if source.endswith('\n'):
1274 source = source[:-1]
1275 out.append(' ' + '\n '.join(source.split('\n')))
1276 return '\n'.join(out)+'\n'
Tim Peters7402f792001-10-02 03:53:41 +00001277
Tim Peters8485b562004-08-04 18:46:34 +00001278 #/////////////////////////////////////////////////////////////////
1279 # DocTest Running
1280 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001281
Tim Peters8485b562004-08-04 18:46:34 +00001282 # A regular expression for handling `want` strings that contain
Tim Peters41a65ea2004-08-13 03:55:05 +00001283 # expected exceptions. It divides `want` into three pieces:
1284 # - the pre-exception output (`want`)
1285 # - the traceback header line (`hdr`)
1286 # - the exception message (`msg`), as generated by
1287 # traceback.format_exception_only()
1288 # `msg` may have multiple lines. We assume/require that the
1289 # exception message is the first non-indented line starting with a word
1290 # character following the traceback header line.
1291 _EXCEPTION_RE = re.compile(r"""
1292 (?P<want> .*?) # suck up everything until traceback header
1293 # Grab the traceback header. Different versions of Python have
1294 # said different things on the first traceback line.
1295 ^(?P<hdr> Traceback\ \(
1296 (?: most\ recent\ call\ last
1297 | innermost\ last
1298 ) \) :
1299 )
1300 \s* $ # toss trailing whitespace on traceback header
1301 .*? # don't blink: absorb stuff until a line *starts* with \w
1302 ^ (?P<msg> \w+ .*)
1303 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001304
Tim Peters8485b562004-08-04 18:46:34 +00001305 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001306 """
Tim Peters8485b562004-08-04 18:46:34 +00001307 Run the examples in `test`. Write the outcome of each example
1308 with one of the `DocTestRunner.report_*` methods, using the
1309 writer function `out`. `compileflags` is the set of compiler
1310 flags that should be used to execute examples. Return a tuple
1311 `(f, t)`, where `t` is the number of examples tried, and `f`
1312 is the number of examples that failed. The examples are run
1313 in the namespace `test.globs`.
1314 """
1315 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001316 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001317
1318 # Save the option flags (since option directives can be used
1319 # to modify them).
1320 original_optionflags = self.optionflags
1321
1322 # Process each example.
1323 for example in test.examples:
Edward Loper74bca7a2004-08-12 02:27:44 +00001324 # Merge in the example's options.
1325 self.optionflags = original_optionflags
1326 if example.options:
1327 for (optionflag, val) in example.options.items():
1328 if val:
1329 self.optionflags |= optionflag
1330 else:
1331 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001332
1333 # Record that we started this example.
1334 tries += 1
1335 self.report_start(out, test, example)
1336
1337 # Run the example in the given context (globs), and record
1338 # any exception that gets raised. (But don't intercept
1339 # keyboard interrupts.)
1340 try:
Tim Peters208ca702004-08-09 04:12:36 +00001341 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001342 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001343 compileflags, 1) in test.globs
1344 exception = None
1345 except KeyboardInterrupt:
1346 raise
1347 except:
1348 exception = sys.exc_info()
1349
Tim Peters208ca702004-08-09 04:12:36 +00001350 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001351 self._fakeout.truncate(0)
1352
1353 # If the example executed without raising any exceptions,
1354 # then verify its output and report its outcome.
1355 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001356 if self._checker.check_output(example.want, got,
1357 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001358 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001359 else:
Tim Peters8485b562004-08-04 18:46:34 +00001360 self.report_failure(out, test, example, got)
1361 failures += 1
1362
1363 # If the example raised an exception, then check if it was
1364 # expected.
1365 else:
1366 exc_info = sys.exc_info()
1367 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1368
1369 # Search the `want` string for an exception. If we don't
1370 # find one, then report an unexpected exception.
1371 m = self._EXCEPTION_RE.match(example.want)
1372 if m is None:
1373 self.report_unexpected_exception(out, test, example,
1374 exc_info)
1375 failures += 1
1376 else:
Tim Peters41a65ea2004-08-13 03:55:05 +00001377 e_want, e_msg = m.group('want', 'msg')
Tim Peters8485b562004-08-04 18:46:34 +00001378 # The test passes iff the pre-exception output and
1379 # the exception description match the values given
1380 # in `want`.
Tim Peters41a65ea2004-08-13 03:55:05 +00001381 if (self._checker.check_output(e_want, got,
Edward Loper34fcb142004-08-09 02:45:41 +00001382 self.optionflags) and
Tim Peters41a65ea2004-08-13 03:55:05 +00001383 self._checker.check_output(e_msg, exc_msg,
Edward Loper34fcb142004-08-09 02:45:41 +00001384 self.optionflags)):
Tim Peters8485b562004-08-04 18:46:34 +00001385 self.report_success(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001386 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001387 else:
1388 self.report_failure(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001389 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001390 failures += 1
1391
1392 # Restore the option flags (in case they were modified)
1393 self.optionflags = original_optionflags
1394
1395 # Record and return the number of failures and tries.
1396 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001397 return failures, tries
1398
Tim Peters8485b562004-08-04 18:46:34 +00001399 def __record_outcome(self, test, f, t):
1400 """
1401 Record the fact that the given DocTest (`test`) generated `f`
1402 failures out of `t` tried examples.
1403 """
1404 f2, t2 = self._name2ft.get(test.name, (0,0))
1405 self._name2ft[test.name] = (f+f2, t+t2)
1406 self.failures += f
1407 self.tries += t
1408
1409 def run(self, test, compileflags=None, out=None, clear_globs=True):
1410 """
1411 Run the examples in `test`, and display the results using the
1412 writer function `out`.
1413
1414 The examples are run in the namespace `test.globs`. If
1415 `clear_globs` is true (the default), then this namespace will
1416 be cleared after the test runs, to help with garbage
1417 collection. If you would like to examine the namespace after
1418 the test completes, then use `clear_globs=False`.
1419
1420 `compileflags` gives the set of flags that should be used by
1421 the Python compiler when running the examples. If not
1422 specified, then it will default to the set of future-import
1423 flags that apply to `globs`.
1424
1425 The output of each example is checked using
1426 `DocTestRunner.check_output`, and the results are formatted by
1427 the `DocTestRunner.report_*` methods.
1428 """
1429 if compileflags is None:
1430 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001431
Tim Peters6c542b72004-08-09 16:43:36 +00001432 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001433 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001434 out = save_stdout.write
1435 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001436
Tim Peters6c542b72004-08-09 16:43:36 +00001437 # Patch pdb.set_trace to restore sys.stdout, so that interactive
1438 # debugging output is visible (not still redirected to self._fakeout).
1439 # Note that we run "the real" pdb.set_trace (captured at doctest
1440 # import time) in our replacement. Because the current run() may
1441 # run another doctest (and so on), the current pdb.set_trace may be
1442 # our set_trace function, which changes sys.stdout. If we called
1443 # a chain of those, we wouldn't be left with the save_stdout
1444 # *this* run() invocation wants.
Jim Fulton356fd192004-08-09 11:34:47 +00001445 def set_trace():
Tim Peters6c542b72004-08-09 16:43:36 +00001446 sys.stdout = save_stdout
Jim Fulton356fd192004-08-09 11:34:47 +00001447 real_pdb_set_trace()
1448
Tim Peters6c542b72004-08-09 16:43:36 +00001449 save_set_trace = pdb.set_trace
1450 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001451 try:
Tim Peters8485b562004-08-04 18:46:34 +00001452 return self.__run(test, compileflags, out)
1453 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001454 sys.stdout = save_stdout
1455 pdb.set_trace = save_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001456 if clear_globs:
1457 test.globs.clear()
1458
1459 #/////////////////////////////////////////////////////////////////
1460 # Summarization
1461 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001462 def summarize(self, verbose=None):
1463 """
Tim Peters8485b562004-08-04 18:46:34 +00001464 Print a summary of all the test cases that have been run by
1465 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1466 the total number of failed examples, and `t` is the total
1467 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001468
Tim Peters8485b562004-08-04 18:46:34 +00001469 The optional `verbose` argument controls how detailed the
1470 summary is. If the verbosity is not specified, then the
1471 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001472 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001473 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001474 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001475 notests = []
1476 passed = []
1477 failed = []
1478 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001479 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001480 name, (f, t) = x
1481 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001482 totalt += t
1483 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001484 if t == 0:
1485 notests.append(name)
1486 elif f == 0:
1487 passed.append( (name, t) )
1488 else:
1489 failed.append(x)
1490 if verbose:
1491 if notests:
1492 print len(notests), "items had no tests:"
1493 notests.sort()
1494 for thing in notests:
1495 print " ", thing
1496 if passed:
1497 print len(passed), "items passed all tests:"
1498 passed.sort()
1499 for thing, count in passed:
1500 print " %3d tests in %s" % (count, thing)
1501 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001502 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001503 print len(failed), "items had failures:"
1504 failed.sort()
1505 for thing, (f, t) in failed:
1506 print " %3d of %3d in %s" % (f, t, thing)
1507 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001508 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001509 print totalt - totalf, "passed and", totalf, "failed."
1510 if totalf:
1511 print "***Test Failed***", totalf, "failures."
1512 elif verbose:
1513 print "Test passed."
1514 return totalf, totalt
1515
Edward Loper34fcb142004-08-09 02:45:41 +00001516class OutputChecker:
1517 """
1518 A class used to check the whether the actual output from a doctest
1519 example matches the expected output. `OutputChecker` defines two
1520 methods: `check_output`, which compares a given pair of outputs,
1521 and returns true if they match; and `output_difference`, which
1522 returns a string describing the differences between two outputs.
1523 """
1524 def check_output(self, want, got, optionflags):
1525 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001526 Return True iff the actual output from an example (`got`)
1527 matches the expected output (`want`). These strings are
1528 always considered to match if they are identical; but
1529 depending on what option flags the test runner is using,
1530 several non-exact match types are also possible. See the
1531 documentation for `TestRunner` for more information about
1532 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001533 """
1534 # Handle the common case first, for efficiency:
1535 # if they're string-identical, always return true.
1536 if got == want:
1537 return True
1538
1539 # The values True and False replaced 1 and 0 as the return
1540 # value for boolean comparisons in Python 2.3.
1541 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1542 if (got,want) == ("True\n", "1\n"):
1543 return True
1544 if (got,want) == ("False\n", "0\n"):
1545 return True
1546
1547 # <BLANKLINE> can be used as a special sequence to signify a
1548 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1549 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1550 # Replace <BLANKLINE> in want with a blank line.
1551 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1552 '', want)
1553 # If a line in got contains only spaces, then remove the
1554 # spaces.
1555 got = re.sub('(?m)^\s*?$', '', got)
1556 if got == want:
1557 return True
1558
1559 # This flag causes doctest to ignore any differences in the
1560 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001561 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001562 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001563 got = ' '.join(got.split())
1564 want = ' '.join(want.split())
1565 if got == want:
1566 return True
1567
1568 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001569 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001570 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001571 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001572 return True
1573
1574 # We didn't find any match; return false.
1575 return False
1576
Tim Petersc6cbab02004-08-22 19:43:28 +00001577 # Should we do a fancy diff?
1578 def _do_a_fancy_diff(self, want, got, optionflags):
1579 # Not unless they asked for a fancy diff.
1580 if not optionflags & (UNIFIED_DIFF |
1581 CONTEXT_DIFF |
1582 NDIFF_DIFF):
1583 return False
1584 # If expected output uses ellipsis, a meaningful fancy diff is
1585 # too hard.
1586 if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1587 return False
1588 # ndiff does intraline difference marking, so can be useful even
1589 # for 1-line inputs.
1590 if optionflags & NDIFF_DIFF:
1591 return True
1592 # The other diff types need at least a few lines to be helpful.
1593 return want.count('\n') > 2 and got.count('\n') > 2
1594
Edward Loper34fcb142004-08-09 02:45:41 +00001595 def output_difference(self, want, got, optionflags):
1596 """
1597 Return a string describing the differences between the
Edward Loper74bca7a2004-08-12 02:27:44 +00001598 expected output for an example (`want`) and the actual output
1599 (`got`). `optionflags` is the set of option flags used to
1600 compare `want` and `got`. `indent` is the indentation of the
1601 original example.
Edward Loper34fcb142004-08-09 02:45:41 +00001602 """
Tim Petersc5049152004-08-22 17:34:58 +00001603
Edward Loper68ba9a62004-08-12 02:43:49 +00001604 # If <BLANKLINE>s are being used, then replace blank lines
1605 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001606 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001607 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001608
1609 # Check if we should use diff. Don't use diff if the actual
1610 # or expected outputs are too short, or if the expected output
1611 # contains an ellipsis marker.
Tim Petersc6cbab02004-08-22 19:43:28 +00001612 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001613 # Split want & got into lines.
1614 want_lines = [l+'\n' for l in want.split('\n')]
1615 got_lines = [l+'\n' for l in got.split('\n')]
1616 # Use difflib to find their differences.
1617 if optionflags & UNIFIED_DIFF:
1618 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1619 fromfile='Expected', tofile='Got')
Tim Petersc6cbab02004-08-22 19:43:28 +00001620 kind = 'unified diff'
Edward Loper34fcb142004-08-09 02:45:41 +00001621 elif optionflags & CONTEXT_DIFF:
1622 diff = difflib.context_diff(want_lines, got_lines, n=2,
1623 fromfile='Expected', tofile='Got')
Tim Petersc6cbab02004-08-22 19:43:28 +00001624 kind = 'context diff'
1625 elif optionflags & NDIFF_DIFF:
1626 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1627 diff = list(engine.compare(want_lines, got_lines))
1628 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001629 else:
1630 assert 0, 'Bad diff option'
1631 # Remove trailing whitespace on diff output.
1632 diff = [line.rstrip() + '\n' for line in diff]
Tim Petersc6cbab02004-08-22 19:43:28 +00001633 return _tag_msg("Differences (" + kind + ")",
Edward Loper34fcb142004-08-09 02:45:41 +00001634 ''.join(diff))
1635
1636 # If we're not using diff, then simply list the expected
1637 # output followed by the actual output.
Jim Fulton07a349c2004-08-22 14:10:00 +00001638 if want.endswith('\n'):
1639 want = want[:-1]
1640 want = ' ' + '\n '.join(want.split('\n'))
1641 if got.endswith('\n'):
1642 got = got[:-1]
1643 got = ' ' + '\n '.join(got.split('\n'))
1644 return "Expected:\n%s\nGot:\n%s\n" % (want, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001645
Tim Peters19397e52004-08-06 22:02:59 +00001646class DocTestFailure(Exception):
1647 """A DocTest example has failed in debugging mode.
1648
1649 The exception instance has variables:
1650
1651 - test: the DocTest object being run
1652
1653 - excample: the Example object that failed
1654
1655 - got: the actual output
1656 """
1657 def __init__(self, test, example, got):
1658 self.test = test
1659 self.example = example
1660 self.got = got
1661
1662 def __str__(self):
1663 return str(self.test)
1664
1665class UnexpectedException(Exception):
1666 """A DocTest example has encountered an unexpected exception
1667
1668 The exception instance has variables:
1669
1670 - test: the DocTest object being run
1671
1672 - excample: the Example object that failed
1673
1674 - exc_info: the exception info
1675 """
1676 def __init__(self, test, example, exc_info):
1677 self.test = test
1678 self.example = example
1679 self.exc_info = exc_info
1680
1681 def __str__(self):
1682 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001683
Tim Peters19397e52004-08-06 22:02:59 +00001684class DebugRunner(DocTestRunner):
1685 r"""Run doc tests but raise an exception as soon as there is a failure.
1686
1687 If an unexpected exception occurs, an UnexpectedException is raised.
1688 It contains the test, the example, and the original exception:
1689
1690 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001691 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1692 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001693 >>> try:
1694 ... runner.run(test)
1695 ... except UnexpectedException, failure:
1696 ... pass
1697
1698 >>> failure.test is test
1699 True
1700
1701 >>> failure.example.want
1702 '42\n'
1703
1704 >>> exc_info = failure.exc_info
1705 >>> raise exc_info[0], exc_info[1], exc_info[2]
1706 Traceback (most recent call last):
1707 ...
1708 KeyError
1709
1710 We wrap the original exception to give the calling application
1711 access to the test and example information.
1712
1713 If the output doesn't match, then a DocTestFailure is raised:
1714
Edward Lopera1ef6112004-08-09 16:14:41 +00001715 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001716 ... >>> x = 1
1717 ... >>> x
1718 ... 2
1719 ... ''', {}, 'foo', 'foo.py', 0)
1720
1721 >>> try:
1722 ... runner.run(test)
1723 ... except DocTestFailure, failure:
1724 ... pass
1725
1726 DocTestFailure objects provide access to the test:
1727
1728 >>> failure.test is test
1729 True
1730
1731 As well as to the example:
1732
1733 >>> failure.example.want
1734 '2\n'
1735
1736 and the actual output:
1737
1738 >>> failure.got
1739 '1\n'
1740
1741 If a failure or error occurs, the globals are left intact:
1742
1743 >>> del test.globs['__builtins__']
1744 >>> test.globs
1745 {'x': 1}
1746
Edward Lopera1ef6112004-08-09 16:14:41 +00001747 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001748 ... >>> x = 2
1749 ... >>> raise KeyError
1750 ... ''', {}, 'foo', 'foo.py', 0)
1751
1752 >>> runner.run(test)
1753 Traceback (most recent call last):
1754 ...
1755 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001756
Tim Peters19397e52004-08-06 22:02:59 +00001757 >>> del test.globs['__builtins__']
1758 >>> test.globs
1759 {'x': 2}
1760
1761 But the globals are cleared if there is no error:
1762
Edward Lopera1ef6112004-08-09 16:14:41 +00001763 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001764 ... >>> x = 2
1765 ... ''', {}, 'foo', 'foo.py', 0)
1766
1767 >>> runner.run(test)
1768 (0, 1)
1769
1770 >>> test.globs
1771 {}
1772
1773 """
1774
1775 def run(self, test, compileflags=None, out=None, clear_globs=True):
1776 r = DocTestRunner.run(self, test, compileflags, out, False)
1777 if clear_globs:
1778 test.globs.clear()
1779 return r
1780
1781 def report_unexpected_exception(self, out, test, example, exc_info):
1782 raise UnexpectedException(test, example, exc_info)
1783
1784 def report_failure(self, out, test, example, got):
1785 raise DocTestFailure(test, example, got)
1786
Tim Peters8485b562004-08-04 18:46:34 +00001787######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001788## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001789######################################################################
1790# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001791
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001792def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001793 report=True, optionflags=0, extraglobs=None,
1794 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001795 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001796 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001797
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001798 Test examples in docstrings in functions and classes reachable
1799 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001800 with m.__doc__. Unless isprivate is specified, private names
1801 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001802
1803 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001804 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001805 function and class docstrings are tested even if the name is private;
1806 strings are tested directly, as if they were docstrings.
1807
1808 Return (#failures, #tests).
1809
1810 See doctest.__doc__ for an overview.
1811
1812 Optional keyword arg "name" gives the name of the module; by default
1813 use m.__name__.
1814
1815 Optional keyword arg "globs" gives a dict to be used as the globals
1816 when executing examples; by default, use m.__dict__. A copy of this
1817 dict is actually used for each docstring, so that each docstring's
1818 examples start with a clean slate.
1819
Tim Peters8485b562004-08-04 18:46:34 +00001820 Optional keyword arg "extraglobs" gives a dictionary that should be
1821 merged into the globals that are used to execute examples. By
1822 default, no extra globals are used. This is new in 2.4.
1823
Tim Peters8a7d2d52001-01-16 07:10:57 +00001824 Optional keyword arg "verbose" prints lots of stuff if true, prints
1825 only failures if false; by default, it's true iff "-v" is in sys.argv.
1826
Tim Peters8a7d2d52001-01-16 07:10:57 +00001827 Optional keyword arg "report" prints a summary at the end when true,
1828 else prints nothing at the end. In verbose mode, the summary is
1829 detailed, else very brief (in fact, empty if all tests passed).
1830
Tim Peters6ebe61f2003-06-27 20:48:05 +00001831 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001832 and defaults to 0. This is new in 2.3. Possible values (see the
1833 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001834
1835 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001836 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001837 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001838 ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001839 UNIFIED_DIFF
Tim Peters8485b562004-08-04 18:46:34 +00001840 CONTEXT_DIFF
Tim Petersf82a9de2004-08-22 20:51:53 +00001841 NDIFF_DIFF
Tim Peters19397e52004-08-06 22:02:59 +00001842
1843 Optional keyword arg "raise_on_error" raises an exception on the
1844 first unexpected exception or failure. This allows failures to be
1845 post-mortem debugged.
1846
Tim Petersf727c6c2004-08-08 01:48:59 +00001847 Deprecated in Python 2.4:
1848 Optional keyword arg "isprivate" specifies a function used to
1849 determine whether a name is private. The default function is
1850 treat all functions as public. Optionally, "isprivate" can be
1851 set to doctest.is_private to skip over functions marked as private
1852 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001853 """
1854
1855 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001856 Advanced tomfoolery: testmod runs methods of a local instance of
1857 class doctest.Tester, then merges the results into (or creates)
1858 global Tester instance doctest.master. Methods of doctest.master
1859 can be called directly too, if you want to do something unusual.
1860 Passing report=0 to testmod is especially useful then, to delay
1861 displaying a summary. Invoke doctest.master.summarize(verbose)
1862 when you're done fiddling.
1863 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001864 if isprivate is not None:
1865 warnings.warn("the isprivate argument is deprecated; "
1866 "examine DocTestFinder.find() lists instead",
1867 DeprecationWarning)
1868
Tim Peters8485b562004-08-04 18:46:34 +00001869 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001870 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001871 # DWA - m will still be None if this wasn't invoked from the command
1872 # line, in which case the following TypeError is about as good an error
1873 # as we should expect
1874 m = sys.modules.get('__main__')
1875
Tim Peters8485b562004-08-04 18:46:34 +00001876 # Check that we were actually given a module.
1877 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001878 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001879
1880 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001881 if name is None:
1882 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001883
1884 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001885 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001886
1887 if raise_on_error:
1888 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1889 else:
1890 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1891
Tim Peters8485b562004-08-04 18:46:34 +00001892 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1893 runner.run(test)
1894
Tim Peters8a7d2d52001-01-16 07:10:57 +00001895 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001896 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001897
Tim Peters8485b562004-08-04 18:46:34 +00001898 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001899
Tim Peters8485b562004-08-04 18:46:34 +00001900def run_docstring_examples(f, globs, verbose=False, name="NoName",
1901 compileflags=None, optionflags=0):
1902 """
1903 Test examples in the given object's docstring (`f`), using `globs`
1904 as globals. Optional argument `name` is used in failure messages.
1905 If the optional argument `verbose` is true, then generate output
1906 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001907
Tim Peters8485b562004-08-04 18:46:34 +00001908 `compileflags` gives the set of flags that should be used by the
1909 Python compiler when running the examples. If not specified, then
1910 it will default to the set of future-import flags that apply to
1911 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001912
Tim Peters8485b562004-08-04 18:46:34 +00001913 Optional keyword arg `optionflags` specifies options for the
1914 testing and output. See the documentation for `testmod` for more
1915 information.
1916 """
1917 # Find, parse, and run all tests in the given module.
1918 finder = DocTestFinder(verbose=verbose, recurse=False)
1919 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1920 for test in finder.find(f, name, globs=globs):
1921 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001922
Tim Peters8485b562004-08-04 18:46:34 +00001923######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001924## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001925######################################################################
1926# This is provided only for backwards compatibility. It's not
1927# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001928
Tim Peters8485b562004-08-04 18:46:34 +00001929class Tester:
1930 def __init__(self, mod=None, globs=None, verbose=None,
1931 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001932
1933 warnings.warn("class Tester is deprecated; "
1934 "use class doctest.DocTestRunner instead",
1935 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001936 if mod is None and globs is None:
1937 raise TypeError("Tester.__init__: must specify mod or globs")
1938 if mod is not None and not _ismodule(mod):
1939 raise TypeError("Tester.__init__: mod must be a module; %r" %
1940 (mod,))
1941 if globs is None:
1942 globs = mod.__dict__
1943 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001944
Tim Peters8485b562004-08-04 18:46:34 +00001945 self.verbose = verbose
1946 self.isprivate = isprivate
1947 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001948 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001949 self.testrunner = DocTestRunner(verbose=verbose,
1950 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001951
Tim Peters8485b562004-08-04 18:46:34 +00001952 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001953 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001954 if self.verbose:
1955 print "Running string", name
1956 (f,t) = self.testrunner.run(test)
1957 if self.verbose:
1958 print f, "of", t, "examples failed in string", name
1959 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001960
Tim Petersf3f57472004-08-08 06:11:48 +00001961 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001962 f = t = 0
1963 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001964 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001965 for test in tests:
1966 (f2, t2) = self.testrunner.run(test)
1967 (f,t) = (f+f2, t+t2)
1968 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001969
Tim Peters8485b562004-08-04 18:46:34 +00001970 def rundict(self, d, name, module=None):
1971 import new
1972 m = new.module(name)
1973 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001974 if module is None:
1975 module = False
1976 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001977
Tim Peters8485b562004-08-04 18:46:34 +00001978 def run__test__(self, d, name):
1979 import new
1980 m = new.module(name)
1981 m.__test__ = d
1982 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001983
Tim Peters8485b562004-08-04 18:46:34 +00001984 def summarize(self, verbose=None):
1985 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001986
Tim Peters8485b562004-08-04 18:46:34 +00001987 def merge(self, other):
1988 d = self.testrunner._name2ft
1989 for name, (f, t) in other.testrunner._name2ft.items():
1990 if name in d:
1991 print "*** Tester.merge: '" + name + "' in both" \
1992 " testers; summing outcomes."
1993 f2, t2 = d[name]
1994 f = f + f2
1995 t = t + t2
1996 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001997
Tim Peters8485b562004-08-04 18:46:34 +00001998######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001999## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002000######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002001
Tim Peters19397e52004-08-06 22:02:59 +00002002class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002003
Edward Loper34fcb142004-08-09 02:45:41 +00002004 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2005 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002006
Jim Fultona643b652004-07-14 19:06:50 +00002007 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002008 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002009 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002010 self._dt_test = test
2011 self._dt_setUp = setUp
2012 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002013
Jim Fultona643b652004-07-14 19:06:50 +00002014 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00002015 if self._dt_setUp is not None:
2016 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00002017
2018 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00002019 if self._dt_tearDown is not None:
2020 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002021
2022 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002023 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002024 old = sys.stdout
2025 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00002026 runner = DocTestRunner(optionflags=self._dt_optionflags,
2027 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002028
Jim Fultona643b652004-07-14 19:06:50 +00002029 try:
Tim Peters19397e52004-08-06 22:02:59 +00002030 runner.DIVIDER = "-"*70
2031 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00002032 finally:
2033 sys.stdout = old
2034
2035 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002036 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002037
Tim Peters19397e52004-08-06 22:02:59 +00002038 def format_failure(self, err):
2039 test = self._dt_test
2040 if test.lineno is None:
2041 lineno = 'unknown line number'
2042 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002043 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002044 lname = '.'.join(test.name.split('.')[-1:])
2045 return ('Failed doctest test for %s\n'
2046 ' File "%s", line %s, in %s\n\n%s'
2047 % (test.name, test.filename, lineno, lname, err)
2048 )
2049
2050 def debug(self):
2051 r"""Run the test case without results and without catching exceptions
2052
2053 The unit test framework includes a debug method on test cases
2054 and test suites to support post-mortem debugging. The test code
2055 is run in such a way that errors are not caught. This way a
2056 caller can catch the errors and initiate post-mortem debugging.
2057
2058 The DocTestCase provides a debug method that raises
2059 UnexpectedException errors if there is an unexepcted
2060 exception:
2061
Edward Lopera1ef6112004-08-09 16:14:41 +00002062 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002063 ... {}, 'foo', 'foo.py', 0)
2064 >>> case = DocTestCase(test)
2065 >>> try:
2066 ... case.debug()
2067 ... except UnexpectedException, failure:
2068 ... pass
2069
2070 The UnexpectedException contains the test, the example, and
2071 the original exception:
2072
2073 >>> failure.test is test
2074 True
2075
2076 >>> failure.example.want
2077 '42\n'
2078
2079 >>> exc_info = failure.exc_info
2080 >>> raise exc_info[0], exc_info[1], exc_info[2]
2081 Traceback (most recent call last):
2082 ...
2083 KeyError
2084
2085 If the output doesn't match, then a DocTestFailure is raised:
2086
Edward Lopera1ef6112004-08-09 16:14:41 +00002087 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002088 ... >>> x = 1
2089 ... >>> x
2090 ... 2
2091 ... ''', {}, 'foo', 'foo.py', 0)
2092 >>> case = DocTestCase(test)
2093
2094 >>> try:
2095 ... case.debug()
2096 ... except DocTestFailure, failure:
2097 ... pass
2098
2099 DocTestFailure objects provide access to the test:
2100
2101 >>> failure.test is test
2102 True
2103
2104 As well as to the example:
2105
2106 >>> failure.example.want
2107 '2\n'
2108
2109 and the actual output:
2110
2111 >>> failure.got
2112 '1\n'
2113
2114 """
2115
Edward Loper34fcb142004-08-09 02:45:41 +00002116 runner = DebugRunner(optionflags=self._dt_optionflags,
2117 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002118 runner.run(self._dt_test)
Jim Fultona643b652004-07-14 19:06:50 +00002119
2120 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002121 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002122
2123 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002124 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002125 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2126
2127 __str__ = __repr__
2128
2129 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002130 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002131
Tim Peters19397e52004-08-06 22:02:59 +00002132def DocTestSuite(module=None, globs=None, extraglobs=None,
2133 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002134 setUp=lambda: None, tearDown=lambda: None,
2135 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002136 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002137 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002138
Tim Peters19397e52004-08-06 22:02:59 +00002139 This converts each documentation string in a module that
2140 contains doctest tests to a unittest test case. If any of the
2141 tests in a doc string fail, then the test case fails. An exception
2142 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002143 (sometimes approximate) line number.
2144
Tim Peters19397e52004-08-06 22:02:59 +00002145 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002146 can be either a module or a module name.
2147
2148 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002149 """
Jim Fultona643b652004-07-14 19:06:50 +00002150
Tim Peters8485b562004-08-04 18:46:34 +00002151 if test_finder is None:
2152 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002153
Tim Peters19397e52004-08-06 22:02:59 +00002154 module = _normalize_module(module)
2155 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2156 if globs is None:
2157 globs = module.__dict__
2158 if not tests: # [XX] why do we want to do this?
2159 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002160
2161 tests.sort()
2162 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002163 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002164 if len(test.examples) == 0:
2165 continue
Tim Peters8485b562004-08-04 18:46:34 +00002166 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002167 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002168 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002169 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002170 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002171 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2172 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002173
2174 return suite
2175
2176class DocFileCase(DocTestCase):
2177
2178 def id(self):
2179 return '_'.join(self._dt_test.name.split('.'))
2180
2181 def __repr__(self):
2182 return self._dt_test.filename
2183 __str__ = __repr__
2184
2185 def format_failure(self, err):
2186 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2187 % (self._dt_test.name, self._dt_test.filename, err)
2188 )
2189
2190def DocFileTest(path, package=None, globs=None,
2191 setUp=None, tearDown=None,
2192 optionflags=0):
2193 package = _normalize_module(package)
2194 name = path.split('/')[-1]
2195 dir = os.path.split(package.__file__)[0]
2196 path = os.path.join(dir, *(path.split('/')))
2197 doc = open(path).read()
2198
2199 if globs is None:
2200 globs = {}
2201
Edward Lopera1ef6112004-08-09 16:14:41 +00002202 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002203
2204 return DocFileCase(test, optionflags, setUp, tearDown)
2205
2206def DocFileSuite(*paths, **kw):
2207 """Creates a suite of doctest files.
2208
2209 One or more text file paths are given as strings. These should
2210 use "/" characters to separate path segments. Paths are relative
2211 to the directory of the calling module, or relative to the package
2212 passed as a keyword argument.
2213
2214 A number of options may be provided as keyword arguments:
2215
2216 package
2217 The name of a Python package. Text-file paths will be
2218 interpreted relative to the directory containing this package.
2219 The package may be supplied as a package object or as a dotted
2220 package name.
2221
2222 setUp
2223 The name of a set-up function. This is called before running the
2224 tests in each file.
2225
2226 tearDown
2227 The name of a tear-down function. This is called after running the
2228 tests in each file.
2229
2230 globs
2231 A dictionary containing initial global variables for the tests.
2232 """
2233 suite = unittest.TestSuite()
2234
2235 # We do this here so that _normalize_module is called at the right
2236 # level. If it were called in DocFileTest, then this function
2237 # would be the caller and we might guess the package incorrectly.
2238 kw['package'] = _normalize_module(kw.get('package'))
2239
2240 for path in paths:
2241 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002242
Tim Petersdb3756d2003-06-29 05:30:48 +00002243 return suite
2244
Tim Peters8485b562004-08-04 18:46:34 +00002245######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002246## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002247######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002248
Tim Peters19397e52004-08-06 22:02:59 +00002249def script_from_examples(s):
2250 r"""Extract script from text with examples.
2251
2252 Converts text with examples to a Python script. Example input is
2253 converted to regular code. Example output and all other words
2254 are converted to comments:
2255
2256 >>> text = '''
2257 ... Here are examples of simple math.
2258 ...
2259 ... Python has super accurate integer addition
2260 ...
2261 ... >>> 2 + 2
2262 ... 5
2263 ...
2264 ... And very friendly error messages:
2265 ...
2266 ... >>> 1/0
2267 ... To Infinity
2268 ... And
2269 ... Beyond
2270 ...
2271 ... You can use logic if you want:
2272 ...
2273 ... >>> if 0:
2274 ... ... blah
2275 ... ... blah
2276 ... ...
2277 ...
2278 ... Ho hum
2279 ... '''
2280
2281 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002282 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002283 #
Edward Lopera5db6002004-08-12 02:41:30 +00002284 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002285 #
2286 2 + 2
2287 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002288 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002289 #
Edward Lopera5db6002004-08-12 02:41:30 +00002290 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002291 #
2292 1/0
2293 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002294 ## To Infinity
2295 ## And
2296 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002297 #
Edward Lopera5db6002004-08-12 02:41:30 +00002298 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002299 #
2300 if 0:
2301 blah
2302 blah
2303 <BLANKLINE>
2304 #
Edward Lopera5db6002004-08-12 02:41:30 +00002305 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002306 """
2307
Edward Lopera1ef6112004-08-09 16:14:41 +00002308 return DocTestParser().get_program(s)
Tim Peters19397e52004-08-06 22:02:59 +00002309
Tim Peters8485b562004-08-04 18:46:34 +00002310def _want_comment(example):
2311 """
Tim Peters19397e52004-08-06 22:02:59 +00002312 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002313 """
Jim Fultona643b652004-07-14 19:06:50 +00002314 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002315 want = example.want
2316 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002317 if want[-1] == '\n':
2318 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002319 want = "\n# ".join(want.split("\n"))
2320 want = "\n# Expected:\n# %s" % want
2321 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002322
2323def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002324 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002325
2326 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002327 test to be debugged and the name (within the module) of the object
2328 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002329 """
Tim Peters8485b562004-08-04 18:46:34 +00002330 module = _normalize_module(module)
2331 tests = DocTestFinder().find(module)
2332 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002333 if not test:
2334 raise ValueError(name, "not found in tests")
2335 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002336 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002337 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002338
Jim Fultona643b652004-07-14 19:06:50 +00002339def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002340 """Debug a single doctest docstring, in argument `src`'"""
2341 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002342 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002343
Jim Fultona643b652004-07-14 19:06:50 +00002344def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002345 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002346 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002347
Tim Petersb6a04d62004-08-23 21:37:56 +00002348 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2349 # docs say, a file so created cannot be opened by name a second time
2350 # on modern Windows boxes, and execfile() needs to open it.
2351 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002352 f = open(srcfilename, 'w')
2353 f.write(src)
2354 f.close()
2355
Tim Petersb6a04d62004-08-23 21:37:56 +00002356 try:
2357 if globs:
2358 globs = globs.copy()
2359 else:
2360 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002361
Tim Petersb6a04d62004-08-23 21:37:56 +00002362 if pm:
2363 try:
2364 execfile(srcfilename, globs, globs)
2365 except:
2366 print sys.exc_info()[1]
2367 pdb.post_mortem(sys.exc_info()[2])
2368 else:
2369 # Note that %r is vital here. '%s' instead can, e.g., cause
2370 # backslashes to get treated as metacharacters on Windows.
2371 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2372
2373 finally:
2374 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002375
Jim Fultona643b652004-07-14 19:06:50 +00002376def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002377 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002378
2379 Provide the module (or dotted name of the module) containing the
2380 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002381 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002382 """
Tim Peters8485b562004-08-04 18:46:34 +00002383 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002384 testsrc = testsource(module, name)
2385 debug_script(testsrc, pm, module.__dict__)
2386
Tim Peters8485b562004-08-04 18:46:34 +00002387######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002388## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002389######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002390class _TestClass:
2391 """
2392 A pointless class, for sanity-checking of docstring testing.
2393
2394 Methods:
2395 square()
2396 get()
2397
2398 >>> _TestClass(13).get() + _TestClass(-12).get()
2399 1
2400 >>> hex(_TestClass(13).square().get())
2401 '0xa9'
2402 """
2403
2404 def __init__(self, val):
2405 """val -> _TestClass object with associated value val.
2406
2407 >>> t = _TestClass(123)
2408 >>> print t.get()
2409 123
2410 """
2411
2412 self.val = val
2413
2414 def square(self):
2415 """square() -> square TestClass's associated value
2416
2417 >>> _TestClass(13).square().get()
2418 169
2419 """
2420
2421 self.val = self.val ** 2
2422 return self
2423
2424 def get(self):
2425 """get() -> return TestClass's associated value.
2426
2427 >>> x = _TestClass(-42)
2428 >>> print x.get()
2429 -42
2430 """
2431
2432 return self.val
2433
2434__test__ = {"_TestClass": _TestClass,
2435 "string": r"""
2436 Example of a string object, searched as-is.
2437 >>> x = 1; y = 2
2438 >>> x + y, x * y
2439 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002440 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002441
Tim Peters6ebe61f2003-06-27 20:48:05 +00002442 "bool-int equivalence": r"""
2443 In 2.2, boolean expressions displayed
2444 0 or 1. By default, we still accept
2445 them. This can be disabled by passing
2446 DONT_ACCEPT_TRUE_FOR_1 to the new
2447 optionflags argument.
2448 >>> 4 == 4
2449 1
2450 >>> 4 == 4
2451 True
2452 >>> 4 > 4
2453 0
2454 >>> 4 > 4
2455 False
2456 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002457
Tim Peters8485b562004-08-04 18:46:34 +00002458 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002459 Blank lines can be marked with <BLANKLINE>:
2460 >>> print 'foo\n\nbar\n'
2461 foo
2462 <BLANKLINE>
2463 bar
2464 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002465 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002466
2467 "ellipsis": r"""
2468 If the ellipsis flag is used, then '...' can be used to
2469 elide substrings in the desired output:
2470 >>> print range(1000) #doctest: +ELLIPSIS
2471 [0, 1, 2, ..., 999]
2472 """,
2473
2474 "whitespace normalization": r"""
2475 If the whitespace normalization flag is used, then
2476 differences in whitespace are ignored.
2477 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2478 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2479 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2480 27, 28, 29]
2481 """,
2482 }
Tim Peters8485b562004-08-04 18:46:34 +00002483
Tim Peters8a7d2d52001-01-16 07:10:57 +00002484def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002485 r = unittest.TextTestRunner()
2486 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002487
2488if __name__ == "__main__":
2489 _test()