blob: 0eced358824a5fdcc2aaa91925888e6e6968ff30 [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8485b562004-08-04 18:46:34 +00002# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
Tim Peters19397e52004-08-06 22:02:59 +00003# Major enhancements and refactoring by:
Tim Peters8485b562004-08-04 18:46:34 +00004# Jim Fulton
5# Edward Loper
Tim Peters8a7d2d52001-01-16 07:10:57 +00006
7# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
8
Martin v. Löwis92816de2004-05-31 19:01:00 +00009r"""Module doctest -- a framework for running examples in docstrings.
Tim Peters8a7d2d52001-01-16 07:10:57 +000010
11NORMAL USAGE
12
Tim Peters80e53142004-08-09 04:34:45 +000013In simplest use, end each module M to be tested with:
Tim Peters8a7d2d52001-01-16 07:10:57 +000014
15def _test():
Tim Peters80e53142004-08-09 04:34:45 +000016 import doctest
17 return doctest.testmod()
Tim Peters8a7d2d52001-01-16 07:10:57 +000018
19if __name__ == "__main__":
20 _test()
21
22Then running the module as a script will cause the examples in the
23docstrings to get executed and verified:
24
25python M.py
26
27This won't display anything unless an example fails, in which case the
28failing example(s) and the cause(s) of the failure(s) are printed to stdout
29(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
30line of output is "Test failed.".
31
32Run it with the -v switch instead:
33
34python M.py -v
35
36and a detailed report of all examples tried is printed to stdout, along
37with assorted summaries at the end.
38
Tim Peters80e53142004-08-09 04:34:45 +000039You can force verbose mode by passing "verbose=True" to testmod, or prohibit
40it by passing "verbose=False". In either of those cases, sys.argv is not
Tim Peters8a7d2d52001-01-16 07:10:57 +000041examined by testmod.
42
43In any case, testmod returns a 2-tuple of ints (f, t), where f is the
44number of docstring examples that failed and t is the total number of
45docstring examples attempted.
46
Tim Peters80e53142004-08-09 04:34:45 +000047There are a variety of other ways to run doctests, including integration
48with the unittest framework, and support for running non-Python text
49files containing doctests. There are also many ways to override parts
50of doctest's default behaviors. See the Library Reference Manual for
51details.
52
Tim Peters8a7d2d52001-01-16 07:10:57 +000053
54WHICH DOCSTRINGS ARE EXAMINED?
55
56+ M.__doc__.
57
58+ f.__doc__ for all functions f in M.__dict__.values(), except those
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000059 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000060
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000061+ C.__doc__ for all classes C in M.__dict__.values(), except those
62 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000063
64+ If M.__test__ exists and "is true", it must be a dict, and
65 each entry maps a (string) name to a function object, class object, or
66 string. Function and class object docstrings found from M.__test__
Tim Peters80e53142004-08-09 04:34:45 +000067 are searched, and strings are searched directly as if they were docstrings.
68 In output, a key K in M.__test__ appears with name
Tim Peters8a7d2d52001-01-16 07:10:57 +000069 <name of M>.__test__.K
70
71Any classes found are recursively searched similarly, to test docstrings in
Tim Peters80e53142004-08-09 04:34:45 +000072their contained methods and nested classes.
Tim Peters8a7d2d52001-01-16 07:10:57 +000073
Tim Peters8a7d2d52001-01-16 07:10:57 +000074
Tim Peters8a7d2d52001-01-16 07:10:57 +000075WHAT'S THE EXECUTION CONTEXT?
76
77By default, each time testmod finds a docstring to test, it uses a *copy*
78of M's globals (so that running tests on a module doesn't change the
79module's real globals, and so that one test in M can't leave behind crumbs
80that accidentally allow another test to work). This means examples can
81freely use any names defined at top-level in M. It also means that sloppy
82imports (see above) can cause examples in external docstrings to use
83globals inappropriate for them.
84
85You can force use of your own dict as the execution context by passing
86"globs=your_dict" to testmod instead. Presumably this would be a copy of
87M.__dict__ merged with the globals from other imported modules.
88
89
Tim Peters8a7d2d52001-01-16 07:10:57 +000090WHAT ABOUT EXCEPTIONS?
91
92No problem, as long as the only output generated by the example is the
93traceback itself. For example:
94
Tim Peters60e23f42001-02-14 00:43:21 +000095 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +000096 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +000097 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +000098 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +000099 >>>
100
Tim Peters80e53142004-08-09 04:34:45 +0000101Note that only the exception type and value are compared.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000102
103
Tim Peters80e53142004-08-09 04:34:45 +0000104SO WHAT DOES A DOCTEST EXAMPLE LOOK LIKE ALREADY!?
Tim Peters8a7d2d52001-01-16 07:10:57 +0000105
106Oh ya. It's easy! In most cases a copy-and-paste of an interactive
107console session works fine -- just make sure the leading whitespace is
108rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
109right, but doctest is not in the business of guessing what you think a tab
110means).
111
112 >>> # comments are ignored
113 >>> x = 12
114 >>> x
115 12
116 >>> if x == 13:
117 ... print "yes"
118 ... else:
119 ... print "no"
120 ... print "NO"
121 ... print "NO!!!"
122 ...
123 no
124 NO
125 NO!!!
126 >>>
127
128Any expected output must immediately follow the final ">>>" or "..." line
129containing the code, and the expected output (if any) extends to the next
130">>>" or all-whitespace line. That's it.
131
132Bummers:
133
Tim Peters8a7d2d52001-01-16 07:10:57 +0000134+ Output to stdout is captured, but not output to stderr (exception
135 tracebacks are captured via a different means).
136
Martin v. Löwis92816de2004-05-31 19:01:00 +0000137+ If you continue a line via backslashing in an interactive session,
138 or for any other reason use a backslash, you should use a raw
139 docstring, which will preserve your backslahses exactly as you type
140 them:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000141
Tim Peters4e0e1b62004-07-07 20:54:48 +0000142 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000143 ... r'''Backslashes in a raw docstring: m\n'''
144 >>> print f.__doc__
145 Backslashes in a raw docstring: m\n
Tim Peters8a7d2d52001-01-16 07:10:57 +0000146
Martin v. Löwis92816de2004-05-31 19:01:00 +0000147 Otherwise, the backslash will be interpreted as part of the string.
148 E.g., the "\n" above would be interpreted as a newline character.
149 Alternatively, you can double each backslash in the doctest version
150 (and not use a raw string):
151
Tim Peters4e0e1b62004-07-07 20:54:48 +0000152 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000153 ... '''Backslashes in a raw docstring: m\\n'''
154 >>> print f.__doc__
155 Backslashes in a raw docstring: m\n
Tim Peters4e0e1b62004-07-07 20:54:48 +0000156
Tim Peters8a7d2d52001-01-16 07:10:57 +0000157The starting column doesn't matter:
158
159>>> assert "Easy!"
160 >>> import math
161 >>> math.floor(1.9)
162 1.0
163
164and as many leading whitespace characters are stripped from the expected
165output as appeared in the initial ">>>" line that triggered it.
166
167If you execute this very file, the examples above will be found and
Tim Peters80e53142004-08-09 04:34:45 +0000168executed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000169"""
Edward Loper8e4a34b2004-08-12 02:34:27 +0000170__docformat__ = 'reStructuredText en'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000171
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000172__all__ = [
Edward Loperb7503ff2004-08-19 19:19:03 +0000173 # 0, Option Flags
174 'register_optionflag',
175 'DONT_ACCEPT_TRUE_FOR_1',
176 'DONT_ACCEPT_BLANKLINE',
177 'NORMALIZE_WHITESPACE',
178 'ELLIPSIS',
Edward Loper71f55af2004-08-26 01:41:51 +0000179 'REPORT_UDIFF',
180 'REPORT_CDIFF',
181 'REPORT_NDIFF',
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')
Edward Loper71f55af2004-08-26 01:41:51 +0000260REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
261REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
262REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
Edward Lopera89f88d2004-08-26 02:45:51 +0000263REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
Edward Loperac20f572004-08-12 02:02:24 +0000264
265# Special string markers for use in `want` strings:
266BLANKLINE_MARKER = '<BLANKLINE>'
267ELLIPSIS_MARKER = '...'
268
Tim Peters8485b562004-08-04 18:46:34 +0000269######################################################################
270## Table of Contents
271######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000272# 1. Utility Functions
273# 2. Example & DocTest -- store test cases
274# 3. DocTest Parser -- extracts examples from strings
275# 4. DocTest Finder -- extracts test cases from objects
276# 5. DocTest Runner -- runs test cases
277# 6. Test Functions -- convenient wrappers for testing
278# 7. Tester Class -- for backwards compatibility
279# 8. Unittest Support
280# 9. Debugging Support
281# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000282
Tim Peters8485b562004-08-04 18:46:34 +0000283######################################################################
284## 1. Utility Functions
285######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000286
287def is_private(prefix, base):
288 """prefix, base -> true iff name prefix + "." + base is "private".
289
290 Prefix may be an empty string, and base does not contain a period.
291 Prefix is ignored (although functions you write conforming to this
292 protocol may make use of it).
293 Return true iff base begins with an (at least one) underscore, but
294 does not both begin and end with (at least) two underscores.
295
296 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000297 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000298 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000299 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000300 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000301 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000302 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000303 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000304 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000305 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000306 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000307 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000308 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000309 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000310 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000311 warnings.warn("is_private is deprecated; it wasn't useful; "
312 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000313 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000314 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
315
Tim Peters8485b562004-08-04 18:46:34 +0000316def _extract_future_flags(globs):
317 """
318 Return the compiler-flags associated with the future features that
319 have been imported into the given namespace (globs).
320 """
321 flags = 0
322 for fname in __future__.all_feature_names:
323 feature = globs.get(fname, None)
324 if feature is getattr(__future__, fname):
325 flags |= feature.compiler_flag
326 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000327
Tim Peters8485b562004-08-04 18:46:34 +0000328def _normalize_module(module, depth=2):
329 """
330 Return the module specified by `module`. In particular:
331 - If `module` is a module, then return module.
332 - If `module` is a string, then import and return the
333 module with that name.
334 - If `module` is None, then return the calling module.
335 The calling module is assumed to be the module of
336 the stack frame at the given depth in the call stack.
337 """
338 if inspect.ismodule(module):
339 return module
340 elif isinstance(module, (str, unicode)):
341 return __import__(module, globals(), locals(), ["*"])
342 elif module is None:
343 return sys.modules[sys._getframe(depth).f_globals['__name__']]
344 else:
345 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000346
Edward Loperaacf0832004-08-26 01:19:50 +0000347def _indent(s, indent=4):
Tim Peters8485b562004-08-04 18:46:34 +0000348 """
Edward Loperaacf0832004-08-26 01:19:50 +0000349 Add the given number of space characters to the beginning every
350 non-blank line in `s`, and return the result.
Tim Peters8485b562004-08-04 18:46:34 +0000351 """
Edward Loperaacf0832004-08-26 01:19:50 +0000352 # This regexp matches the start of non-blank lines:
353 return re.sub('(?m)^(?!$)', indent*' ', s)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000354
Edward Loper8e4a34b2004-08-12 02:34:27 +0000355def _exception_traceback(exc_info):
356 """
357 Return a string containing a traceback message for the given
358 exc_info tuple (as returned by sys.exc_info()).
359 """
360 # Get a traceback message.
361 excout = StringIO()
362 exc_type, exc_val, exc_tb = exc_info
363 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
364 return excout.getvalue()
365
Tim Peters8485b562004-08-04 18:46:34 +0000366# Override some StringIO methods.
367class _SpoofOut(StringIO):
368 def getvalue(self):
369 result = StringIO.getvalue(self)
370 # If anything at all was written, make sure there's a trailing
371 # newline. There's no way for the expected output to indicate
372 # that a trailing newline is missing.
373 if result and not result.endswith("\n"):
374 result += "\n"
375 # Prevent softspace from screwing up the next test case, in
376 # case they used print with a trailing comma in an example.
377 if hasattr(self, "softspace"):
378 del self.softspace
379 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000380
Tim Peters8485b562004-08-04 18:46:34 +0000381 def truncate(self, size=None):
382 StringIO.truncate(self, size)
383 if hasattr(self, "softspace"):
384 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000385
Tim Peters26b3ebb2004-08-19 08:10:08 +0000386# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000387def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000388 """
389 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000390 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000391 False
392 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000393 if ELLIPSIS_MARKER not in want:
394 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000395
Tim Peters26b3ebb2004-08-19 08:10:08 +0000396 # Find "the real" strings.
397 ws = want.split(ELLIPSIS_MARKER)
398 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000399
Tim Petersdc5de3b2004-08-19 14:06:20 +0000400 # Deal with exact matches possibly needed at one or both ends.
401 startpos, endpos = 0, len(got)
402 w = ws[0]
403 if w: # starts with exact match
404 if got.startswith(w):
405 startpos = len(w)
406 del ws[0]
407 else:
408 return False
409 w = ws[-1]
410 if w: # ends with exact match
411 if got.endswith(w):
412 endpos -= len(w)
413 del ws[-1]
414 else:
415 return False
416
417 if startpos > endpos:
418 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000419 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000420 return False
421
422 # For the rest, we only need to find the leftmost non-overlapping
423 # match for each piece. If there's no overall match that way alone,
424 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000425 for w in ws:
426 # w may be '' at times, if there are consecutive ellipses, or
427 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000428 # Search for an empty string succeeds, and doesn't change startpos.
429 startpos = got.find(w, startpos, endpos)
430 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000431 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000432 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000433
Tim Petersdc5de3b2004-08-19 14:06:20 +0000434 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000435
Edward Loper00f8da72004-08-26 18:05:07 +0000436def _comment_line(line):
437 "Return a commented form of the given line"
438 line = line.rstrip()
439 if line:
440 return '# '+line
441 else:
442 return '#'
443
Tim Peters8485b562004-08-04 18:46:34 +0000444######################################################################
445## 2. Example & DocTest
446######################################################################
447## - An "example" is a <source, want> pair, where "source" is a
448## fragment of source code, and "want" is the expected output for
449## "source." The Example class also includes information about
450## where the example was extracted from.
451##
Edward Lopera1ef6112004-08-09 16:14:41 +0000452## - A "doctest" is a collection of examples, typically extracted from
453## a string (such as an object's docstring). The DocTest class also
454## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000455
Tim Peters8485b562004-08-04 18:46:34 +0000456class Example:
457 """
458 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000459 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000460
Edward Loper74bca7a2004-08-12 02:27:44 +0000461 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000462 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000463
Edward Loper74bca7a2004-08-12 02:27:44 +0000464 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000465 from stdout, or a traceback in case of exception). `want` ends
466 with a newline unless it's empty, in which case it's an empty
467 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000468
Edward Lopera6b68322004-08-26 00:05:43 +0000469 - exc_msg: The exception message generated by the example, if
470 the example is expected to generate an exception; or `None` if
471 it is not expected to generate an exception. This exception
472 message is compared against the return value of
473 `traceback.format_exception_only()`. `exc_msg` ends with a
474 newline unless it's `None`. The constructor adds a newline
475 if needed.
476
Edward Loper74bca7a2004-08-12 02:27:44 +0000477 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000478 this Example where the Example begins. This line number is
479 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000480
481 - indent: The example's indentation in the DocTest string.
482 I.e., the number of space characters that preceed the
483 example's first prompt.
484
485 - options: A dictionary mapping from option flags to True or
486 False, which is used to override default options for this
487 example. Any option flags not contained in this dictionary
488 are left at their default value (as specified by the
489 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000490 """
Edward Lopera6b68322004-08-26 00:05:43 +0000491 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
492 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000493 # Normalize inputs.
494 if not source.endswith('\n'):
495 source += '\n'
496 if want and not want.endswith('\n'):
497 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000498 if exc_msg is not None and not exc_msg.endswith('\n'):
499 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000500 # Store properties.
501 self.source = source
502 self.want = want
503 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000504 self.indent = indent
505 if options is None: options = {}
506 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000507 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000508
Tim Peters8485b562004-08-04 18:46:34 +0000509class DocTest:
510 """
511 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000512 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000513
Tim Peters8485b562004-08-04 18:46:34 +0000514 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000515
Tim Peters8485b562004-08-04 18:46:34 +0000516 - globs: The namespace (aka globals) that the examples should
517 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000518
Tim Peters8485b562004-08-04 18:46:34 +0000519 - name: A name identifying the DocTest (typically, the name of
520 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000521
Tim Peters8485b562004-08-04 18:46:34 +0000522 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000523 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000524
Tim Peters8485b562004-08-04 18:46:34 +0000525 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000526 begins, or `None` if the line number is unavailable. This
527 line number is zero-based, with respect to the beginning of
528 the file.
529
530 - docstring: The string that the examples were extracted from,
531 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000532 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000533 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000534 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000535 Create a new DocTest containing the given examples. The
536 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000537 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000538 assert not isinstance(examples, basestring), \
539 "DocTest no longer accepts str; use DocTestParser instead"
540 self.examples = examples
541 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000542 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000543 self.name = name
544 self.filename = filename
545 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000546
547 def __repr__(self):
548 if len(self.examples) == 0:
549 examples = 'no examples'
550 elif len(self.examples) == 1:
551 examples = '1 example'
552 else:
553 examples = '%d examples' % len(self.examples)
554 return ('<DocTest %s from %s:%s (%s)>' %
555 (self.name, self.filename, self.lineno, examples))
556
557
558 # This lets us sort tests by name:
559 def __cmp__(self, other):
560 if not isinstance(other, DocTest):
561 return -1
562 return cmp((self.name, self.filename, self.lineno, id(self)),
563 (other.name, other.filename, other.lineno, id(other)))
564
565######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000566## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000567######################################################################
568
Edward Lopera1ef6112004-08-09 16:14:41 +0000569class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000570 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000571 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000572 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000573 # This regular expression is used to find doctest examples in a
574 # string. It defines three groups: `source` is the source code
575 # (including leading indentation and prompts); `indent` is the
576 # indentation of the first (PS1) line of the source code; and
577 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000578 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000579 # Source consists of a PS1 line followed by zero or more PS2 lines.
580 (?P<source>
581 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
582 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
583 \n?
584 # Want consists of any non-blank lines that do not start with PS1.
585 (?P<want> (?:(?![ ]*$) # Not a blank line
586 (?![ ]*>>>) # Not a line starting with PS1
587 .*$\n? # But any other line
588 )*)
589 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000590
Edward Lopera6b68322004-08-26 00:05:43 +0000591 # A regular expression for handling `want` strings that contain
592 # expected exceptions. It divides `want` into three pieces:
593 # - the traceback header line (`hdr`)
594 # - the traceback stack (`stack`)
595 # - the exception message (`msg`), as generated by
596 # traceback.format_exception_only()
597 # `msg` may have multiple lines. We assume/require that the
598 # exception message is the first non-indented line starting with a word
599 # character following the traceback header line.
600 _EXCEPTION_RE = re.compile(r"""
601 # Grab the traceback header. Different versions of Python have
602 # said different things on the first traceback line.
603 ^(?P<hdr> Traceback\ \(
604 (?: most\ recent\ call\ last
605 | innermost\ last
606 ) \) :
607 )
608 \s* $ # toss trailing whitespace on the header.
609 (?P<stack> .*?) # don't blink: absorb stuff until...
610 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
611 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
612
Tim Peters7ea48dd2004-08-13 01:52:59 +0000613 # A callable returning a true value iff its argument is a blank line
614 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000615 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000616
Edward Loper00f8da72004-08-26 18:05:07 +0000617 def parse(self, string, name='<string>'):
618 """
619 Divide the given string into examples and intervening text,
620 and return them as a list of alternating Examples and strings.
621 Line numbers for the Examples are 0-based. The optional
622 argument `name` is a name identifying this string, and is only
623 used for error messages.
624 """
625 string = string.expandtabs()
626 # If all lines begin with the same indentation, then strip it.
627 min_indent = self._min_indent(string)
628 if min_indent > 0:
629 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
630
631 output = []
632 charno, lineno = 0, 0
633 # Find all doctest examples in the string:
634 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
635 # Add the pre-example text to `output`.
636 output.append(string[charno:m.start()])
637 # Update lineno (lines before this example)
638 lineno += string.count('\n', charno, m.start())
639 # Extract info from the regexp match.
640 (source, options, want, exc_msg) = \
641 self._parse_example(m, name, lineno)
642 # Create an Example, and add it to the list.
643 if not self._IS_BLANK_OR_COMMENT(source):
644 output.append( Example(source, want, exc_msg,
645 lineno=lineno,
646 indent=min_indent+len(m.group('indent')),
647 options=options) )
648 # Update lineno (lines inside this example)
649 lineno += string.count('\n', m.start(), m.end())
650 # Update charno.
651 charno = m.end()
652 # Add any remaining post-example text to `output`.
653 output.append(string[charno:])
654 return output
655
Edward Lopera1ef6112004-08-09 16:14:41 +0000656 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000657 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000658 Extract all doctest examples from the given string, and
659 collect them into a `DocTest` object.
660
661 `globs`, `name`, `filename`, and `lineno` are attributes for
662 the new `DocTest` object. See the documentation for `DocTest`
663 for more information.
664 """
665 return DocTest(self.get_examples(string, name), globs,
666 name, filename, lineno, string)
667
668 def get_examples(self, string, name='<string>'):
669 """
670 Extract all doctest examples from the given string, and return
671 them as a list of `Example` objects. Line numbers are
672 0-based, because it's most common in doctests that nothing
673 interesting appears on the same line as opening triple-quote,
674 and so the first interesting line is called \"line 1\" then.
675
676 The optional argument `name` is a name identifying this
677 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000678 """
Edward Loper00f8da72004-08-26 18:05:07 +0000679 return [x for x in self.parse(string, name)
680 if isinstance(x, Example)]
Edward Loper7c748462004-08-09 02:06:06 +0000681
Edward Loper74bca7a2004-08-12 02:27:44 +0000682 def _parse_example(self, m, name, lineno):
683 """
684 Given a regular expression match from `_EXAMPLE_RE` (`m`),
685 return a pair `(source, want)`, where `source` is the matched
686 example's source code (with prompts and indentation stripped);
687 and `want` is the example's expected output (with indentation
688 stripped).
689
690 `name` is the string's name, and `lineno` is the line number
691 where the example starts; both are used for error messages.
692 """
Edward Loper7c748462004-08-09 02:06:06 +0000693 # Get the example's indentation level.
694 indent = len(m.group('indent'))
695
696 # Divide source into lines; check that they're properly
697 # indented; and then strip their indentation & prompts.
698 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000699 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000700 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000701 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000702
Tim Petersc5049152004-08-22 17:34:58 +0000703 # Divide want into lines; check that it's properly indented; and
704 # then strip the indentation. Spaces before the last newline should
705 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000706 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000707 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000708 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
709 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000710 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000711 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000712 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000713
Edward Lopera6b68322004-08-26 00:05:43 +0000714 # If `want` contains a traceback message, then extract it.
715 m = self._EXCEPTION_RE.match(want)
716 if m:
717 exc_msg = m.group('msg')
718 else:
719 exc_msg = None
720
Edward Loper00f8da72004-08-26 18:05:07 +0000721 # Extract options from the source.
722 options = self._find_options(source, name, lineno)
723
724 return source, options, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000725
Edward Loper74bca7a2004-08-12 02:27:44 +0000726 # This regular expression looks for option directives in the
727 # source code of an example. Option directives are comments
728 # starting with "doctest:". Warning: this may give false
729 # positives for string-literals that contain the string
730 # "#doctest:". Eliminating these false positives would require
731 # actually parsing the string; but we limit them by ignoring any
732 # line containing "#doctest:" that is *followed* by a quote mark.
733 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
734 re.MULTILINE)
735
736 def _find_options(self, source, name, lineno):
737 """
738 Return a dictionary containing option overrides extracted from
739 option directives in the given source string.
740
741 `name` is the string's name, and `lineno` is the line number
742 where the example starts; both are used for error messages.
743 """
744 options = {}
745 # (note: with the current regexp, this will match at most once:)
746 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
747 option_strings = m.group(1).replace(',', ' ').split()
748 for option in option_strings:
749 if (option[0] not in '+-' or
750 option[1:] not in OPTIONFLAGS_BY_NAME):
751 raise ValueError('line %r of the doctest for %s '
752 'has an invalid option: %r' %
753 (lineno+1, name, option))
754 flag = OPTIONFLAGS_BY_NAME[option[1:]]
755 options[flag] = (option[0] == '+')
756 if options and self._IS_BLANK_OR_COMMENT(source):
757 raise ValueError('line %r of the doctest for %s has an option '
758 'directive on a line with no example: %r' %
759 (lineno, name, source))
760 return options
761
Edward Lopera5db6002004-08-12 02:41:30 +0000762 # This regular expression finds the indentation of every non-blank
763 # line in a string.
Edward Loper00f8da72004-08-26 18:05:07 +0000764 _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
Edward Lopera5db6002004-08-12 02:41:30 +0000765
766 def _min_indent(self, s):
767 "Return the minimum indentation of any non-blank line in `s`"
Edward Loper00f8da72004-08-26 18:05:07 +0000768 indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
769 if len(indents) > 0:
770 return min(indents)
Tim Petersdd0e4752004-08-09 03:31:56 +0000771 else:
Edward Loper00f8da72004-08-26 18:05:07 +0000772 return 0
Edward Loper7c748462004-08-09 02:06:06 +0000773
Edward Lopera1ef6112004-08-09 16:14:41 +0000774 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000775 """
776 Given the lines of a source string (including prompts and
777 leading indentation), check to make sure that every prompt is
778 followed by a space character. If any line is not followed by
779 a space character, then raise ValueError.
780 """
Edward Loper7c748462004-08-09 02:06:06 +0000781 for i, line in enumerate(lines):
782 if len(line) >= indent+4 and line[indent+3] != ' ':
783 raise ValueError('line %r of the docstring for %s '
784 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000785 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000786 line[indent:indent+3], line))
787
Edward Lopera1ef6112004-08-09 16:14:41 +0000788 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000789 """
790 Check that every line in the given list starts with the given
791 prefix; if any line does not, then raise a ValueError.
792 """
Edward Loper7c748462004-08-09 02:06:06 +0000793 for i, line in enumerate(lines):
794 if line and not line.startswith(prefix):
795 raise ValueError('line %r of the docstring for %s has '
796 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000797 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000798
799
800######################################################################
801## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000802######################################################################
803
804class DocTestFinder:
805 """
806 A class used to extract the DocTests that are relevant to a given
807 object, from its docstring and the docstrings of its contained
808 objects. Doctests can currently be extracted from the following
809 object types: modules, functions, classes, methods, staticmethods,
810 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000811 """
812
Edward Lopera1ef6112004-08-09 16:14:41 +0000813 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000814 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000815 """
816 Create a new doctest finder.
817
Edward Lopera1ef6112004-08-09 16:14:41 +0000818 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000819 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000820 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000821 signature for this factory function should match the signature
822 of the DocTest constructor.
823
Tim Peters8485b562004-08-04 18:46:34 +0000824 If the optional argument `recurse` is false, then `find` will
825 only examine the given object, and not any contained objects.
826 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000827 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000828 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000829 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000830 # _namefilter is undocumented, and exists only for temporary backward-
831 # compatibility support of testmod's deprecated isprivate mess.
832 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000833
834 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000835 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000836 """
837 Return a list of the DocTests that are defined by the given
838 object's docstring, or by any of its contained objects'
839 docstrings.
840
841 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000842 the given object. If the module is not specified or is None, then
843 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000844 correct module. The object's module is used:
845
846 - As a default namespace, if `globs` is not specified.
847 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000848 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000849 - To find the name of the file containing the object.
850 - To help find the line number of the object within its
851 file.
852
Tim Petersf3f57472004-08-08 06:11:48 +0000853 Contained objects whose module does not match `module` are ignored.
854
855 If `module` is False, no attempt to find the module will be made.
856 This is obscure, of use mostly in tests: if `module` is False, or
857 is None but cannot be found automatically, then all objects are
858 considered to belong to the (non-existent) module, so all contained
859 objects will (recursively) be searched for doctests.
860
Tim Peters8485b562004-08-04 18:46:34 +0000861 The globals for each DocTest is formed by combining `globs`
862 and `extraglobs` (bindings in `extraglobs` override bindings
863 in `globs`). A new copy of the globals dictionary is created
864 for each DocTest. If `globs` is not specified, then it
865 defaults to the module's `__dict__`, if specified, or {}
866 otherwise. If `extraglobs` is not specified, then it defaults
867 to {}.
868
Tim Peters8485b562004-08-04 18:46:34 +0000869 """
870 # If name was not specified, then extract it from the object.
871 if name is None:
872 name = getattr(obj, '__name__', None)
873 if name is None:
874 raise ValueError("DocTestFinder.find: name must be given "
875 "when obj.__name__ doesn't exist: %r" %
876 (type(obj),))
877
878 # Find the module that contains the given object (if obj is
879 # a module, then module=obj.). Note: this may fail, in which
880 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000881 if module is False:
882 module = None
883 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000884 module = inspect.getmodule(obj)
885
886 # Read the module's source code. This is used by
887 # DocTestFinder._find_lineno to find the line number for a
888 # given object's docstring.
889 try:
890 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
891 source_lines = linecache.getlines(file)
892 if not source_lines:
893 source_lines = None
894 except TypeError:
895 source_lines = None
896
897 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000898 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000899 if module is None:
900 globs = {}
901 else:
902 globs = module.__dict__.copy()
903 else:
904 globs = globs.copy()
905 if extraglobs is not None:
906 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000907
Tim Peters8485b562004-08-04 18:46:34 +0000908 # Recursively expore `obj`, extracting DocTests.
909 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000910 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000911 return tests
912
913 def _filter(self, obj, prefix, base):
914 """
915 Return true if the given object should not be examined.
916 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000917 return (self._namefilter is not None and
918 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000919
920 def _from_module(self, module, object):
921 """
922 Return true if the given object is defined in the given
923 module.
924 """
925 if module is None:
926 return True
927 elif inspect.isfunction(object):
928 return module.__dict__ is object.func_globals
929 elif inspect.isclass(object):
930 return module.__name__ == object.__module__
931 elif inspect.getmodule(object) is not None:
932 return module is inspect.getmodule(object)
933 elif hasattr(object, '__module__'):
934 return module.__name__ == object.__module__
935 elif isinstance(object, property):
936 return True # [XX] no way not be sure.
937 else:
938 raise ValueError("object must be a class or function")
939
Tim Petersf3f57472004-08-08 06:11:48 +0000940 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000941 """
942 Find tests for the given object and any contained objects, and
943 add them to `tests`.
944 """
945 if self._verbose:
946 print 'Finding tests in %s' % name
947
948 # If we've already processed this object, then ignore it.
949 if id(obj) in seen:
950 return
951 seen[id(obj)] = 1
952
953 # Find a test for this object, and add it to the list of tests.
954 test = self._get_test(obj, name, module, globs, source_lines)
955 if test is not None:
956 tests.append(test)
957
958 # Look for tests in a module's contained objects.
959 if inspect.ismodule(obj) and self._recurse:
960 for valname, val in obj.__dict__.items():
961 # Check if this contained object should be ignored.
962 if self._filter(val, name, valname):
963 continue
964 valname = '%s.%s' % (name, valname)
965 # Recurse to functions & classes.
966 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000967 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000968 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000969 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000970
971 # Look for tests in a module's __test__ dictionary.
972 if inspect.ismodule(obj) and self._recurse:
973 for valname, val in getattr(obj, '__test__', {}).items():
974 if not isinstance(valname, basestring):
975 raise ValueError("DocTestFinder.find: __test__ keys "
976 "must be strings: %r" %
977 (type(valname),))
978 if not (inspect.isfunction(val) or inspect.isclass(val) or
979 inspect.ismethod(val) or inspect.ismodule(val) or
980 isinstance(val, basestring)):
981 raise ValueError("DocTestFinder.find: __test__ values "
982 "must be strings, functions, methods, "
983 "classes, or modules: %r" %
984 (type(val),))
985 valname = '%s.%s' % (name, valname)
986 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000987 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000988
989 # Look for tests in a class's contained objects.
990 if inspect.isclass(obj) and self._recurse:
991 for valname, val in obj.__dict__.items():
992 # Check if this contained object should be ignored.
993 if self._filter(val, name, valname):
994 continue
995 # Special handling for staticmethod/classmethod.
996 if isinstance(val, staticmethod):
997 val = getattr(obj, valname)
998 if isinstance(val, classmethod):
999 val = getattr(obj, valname).im_func
1000
1001 # Recurse to methods, properties, and nested classes.
1002 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001003 isinstance(val, property)) and
1004 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001005 valname = '%s.%s' % (name, valname)
1006 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001007 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001008
1009 def _get_test(self, obj, name, module, globs, source_lines):
1010 """
1011 Return a DocTest for the given object, if it defines a docstring;
1012 otherwise, return None.
1013 """
1014 # Extract the object's docstring. If it doesn't have one,
1015 # then return None (no test for this object).
1016 if isinstance(obj, basestring):
1017 docstring = obj
1018 else:
1019 try:
1020 if obj.__doc__ is None:
1021 return None
1022 docstring = str(obj.__doc__)
1023 except (TypeError, AttributeError):
1024 return None
1025
1026 # Don't bother if the docstring is empty.
1027 if not docstring:
1028 return None
1029
1030 # Find the docstring's location in the file.
1031 lineno = self._find_lineno(obj, source_lines)
1032
1033 # Return a DocTest for this object.
1034 if module is None:
1035 filename = None
1036 else:
1037 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001038 if filename[-4:] in (".pyc", ".pyo"):
1039 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001040 return self._parser.get_doctest(docstring, globs, name,
1041 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001042
1043 def _find_lineno(self, obj, source_lines):
1044 """
1045 Return a line number of the given object's docstring. Note:
1046 this method assumes that the object has a docstring.
1047 """
1048 lineno = None
1049
1050 # Find the line number for modules.
1051 if inspect.ismodule(obj):
1052 lineno = 0
1053
1054 # Find the line number for classes.
1055 # Note: this could be fooled if a class is defined multiple
1056 # times in a single file.
1057 if inspect.isclass(obj):
1058 if source_lines is None:
1059 return None
1060 pat = re.compile(r'^\s*class\s*%s\b' %
1061 getattr(obj, '__name__', '-'))
1062 for i, line in enumerate(source_lines):
1063 if pat.match(line):
1064 lineno = i
1065 break
1066
1067 # Find the line number for functions & methods.
1068 if inspect.ismethod(obj): obj = obj.im_func
1069 if inspect.isfunction(obj): obj = obj.func_code
1070 if inspect.istraceback(obj): obj = obj.tb_frame
1071 if inspect.isframe(obj): obj = obj.f_code
1072 if inspect.iscode(obj):
1073 lineno = getattr(obj, 'co_firstlineno', None)-1
1074
1075 # Find the line number where the docstring starts. Assume
1076 # that it's the first line that begins with a quote mark.
1077 # Note: this could be fooled by a multiline function
1078 # signature, where a continuation line begins with a quote
1079 # mark.
1080 if lineno is not None:
1081 if source_lines is None:
1082 return lineno+1
1083 pat = re.compile('(^|.*:)\s*\w*("|\')')
1084 for lineno in range(lineno, len(source_lines)):
1085 if pat.match(source_lines[lineno]):
1086 return lineno
1087
1088 # We couldn't find the line number.
1089 return None
1090
1091######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001092## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001093######################################################################
1094
Tim Peters8485b562004-08-04 18:46:34 +00001095class DocTestRunner:
1096 """
1097 A class used to run DocTest test cases, and accumulate statistics.
1098 The `run` method is used to process a single DocTest case. It
1099 returns a tuple `(f, t)`, where `t` is the number of test cases
1100 tried, and `f` is the number of test cases that failed.
1101
1102 >>> tests = DocTestFinder().find(_TestClass)
1103 >>> runner = DocTestRunner(verbose=False)
1104 >>> for test in tests:
1105 ... print runner.run(test)
1106 (0, 2)
1107 (0, 1)
1108 (0, 2)
1109 (0, 2)
1110
1111 The `summarize` method prints a summary of all the test cases that
1112 have been run by the runner, and returns an aggregated `(f, t)`
1113 tuple:
1114
1115 >>> runner.summarize(verbose=1)
1116 4 items passed all tests:
1117 2 tests in _TestClass
1118 2 tests in _TestClass.__init__
1119 2 tests in _TestClass.get
1120 1 tests in _TestClass.square
1121 7 tests in 4 items.
1122 7 passed and 0 failed.
1123 Test passed.
1124 (0, 7)
1125
1126 The aggregated number of tried examples and failed examples is
1127 also available via the `tries` and `failures` attributes:
1128
1129 >>> runner.tries
1130 7
1131 >>> runner.failures
1132 0
1133
1134 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001135 by an `OutputChecker`. This comparison may be customized with a
1136 number of option flags; see the documentation for `testmod` for
1137 more information. If the option flags are insufficient, then the
1138 comparison may also be customized by passing a subclass of
1139 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001140
1141 The test runner's display output can be controlled in two ways.
1142 First, an output function (`out) can be passed to
1143 `TestRunner.run`; this function will be called with strings that
1144 should be displayed. It defaults to `sys.stdout.write`. If
1145 capturing the output is not sufficient, then the display output
1146 can be also customized by subclassing DocTestRunner, and
1147 overriding the methods `report_start`, `report_success`,
1148 `report_unexpected_exception`, and `report_failure`.
1149 """
1150 # This divider string is used to separate failure messages, and to
1151 # separate sections of the summary.
1152 DIVIDER = "*" * 70
1153
Edward Loper34fcb142004-08-09 02:45:41 +00001154 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001155 """
1156 Create a new test runner.
1157
Edward Loper34fcb142004-08-09 02:45:41 +00001158 Optional keyword arg `checker` is the `OutputChecker` that
1159 should be used to compare the expected outputs and actual
1160 outputs of doctest examples.
1161
Tim Peters8485b562004-08-04 18:46:34 +00001162 Optional keyword arg 'verbose' prints lots of stuff if true,
1163 only failures if false; by default, it's true iff '-v' is in
1164 sys.argv.
1165
1166 Optional argument `optionflags` can be used to control how the
1167 test runner compares expected output to actual output, and how
1168 it displays failures. See the documentation for `testmod` for
1169 more information.
1170 """
Edward Loper34fcb142004-08-09 02:45:41 +00001171 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001172 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001173 verbose = '-v' in sys.argv
1174 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001175 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001176 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001177
Tim Peters8485b562004-08-04 18:46:34 +00001178 # Keep track of the examples we've run.
1179 self.tries = 0
1180 self.failures = 0
1181 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001182
Tim Peters8485b562004-08-04 18:46:34 +00001183 # Create a fake output target for capturing doctest output.
1184 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001185
Tim Peters8485b562004-08-04 18:46:34 +00001186 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001187 # Reporting methods
1188 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001189
Tim Peters8485b562004-08-04 18:46:34 +00001190 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001191 """
Tim Peters8485b562004-08-04 18:46:34 +00001192 Report that the test runner is about to process the given
1193 example. (Only displays a message if verbose=True)
1194 """
1195 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001196 if example.want:
1197 out('Trying:\n' + _indent(example.source) +
1198 'Expecting:\n' + _indent(example.want))
1199 else:
1200 out('Trying:\n' + _indent(example.source) +
1201 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001202
Tim Peters8485b562004-08-04 18:46:34 +00001203 def report_success(self, out, test, example, got):
1204 """
1205 Report that the given example ran successfully. (Only
1206 displays a message if verbose=True)
1207 """
1208 if self._verbose:
1209 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001210
Tim Peters8485b562004-08-04 18:46:34 +00001211 def report_failure(self, out, test, example, got):
1212 """
1213 Report that the given example failed.
1214 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001215 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001216 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001217
Tim Peters8485b562004-08-04 18:46:34 +00001218 def report_unexpected_exception(self, out, test, example, exc_info):
1219 """
1220 Report that the given example raised an unexpected exception.
1221 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001222 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001223 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001224
Edward Loper8e4a34b2004-08-12 02:34:27 +00001225 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001226 out = [self.DIVIDER]
1227 if test.filename:
1228 if test.lineno is not None and example.lineno is not None:
1229 lineno = test.lineno + example.lineno + 1
1230 else:
1231 lineno = '?'
1232 out.append('File "%s", line %s, in %s' %
1233 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001234 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001235 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1236 out.append('Failed example:')
1237 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001238 out.append(_indent(source))
1239 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001240
Tim Peters8485b562004-08-04 18:46:34 +00001241 #/////////////////////////////////////////////////////////////////
1242 # DocTest Running
1243 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001244
Tim Peters8485b562004-08-04 18:46:34 +00001245 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001246 """
Tim Peters8485b562004-08-04 18:46:34 +00001247 Run the examples in `test`. Write the outcome of each example
1248 with one of the `DocTestRunner.report_*` methods, using the
1249 writer function `out`. `compileflags` is the set of compiler
1250 flags that should be used to execute examples. Return a tuple
1251 `(f, t)`, where `t` is the number of examples tried, and `f`
1252 is the number of examples that failed. The examples are run
1253 in the namespace `test.globs`.
1254 """
1255 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001256 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001257
1258 # Save the option flags (since option directives can be used
1259 # to modify them).
1260 original_optionflags = self.optionflags
1261
1262 # Process each example.
1263 for example in test.examples:
Edward Lopera89f88d2004-08-26 02:45:51 +00001264 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1265 # reporting after the first failure.
1266 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1267 failures > 0)
1268
Edward Loper74bca7a2004-08-12 02:27:44 +00001269 # Merge in the example's options.
1270 self.optionflags = original_optionflags
1271 if example.options:
1272 for (optionflag, val) in example.options.items():
1273 if val:
1274 self.optionflags |= optionflag
1275 else:
1276 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001277
1278 # Record that we started this example.
1279 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001280 if not quiet:
1281 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001282
1283 # Run the example in the given context (globs), and record
1284 # any exception that gets raised. (But don't intercept
1285 # keyboard interrupts.)
1286 try:
Tim Peters208ca702004-08-09 04:12:36 +00001287 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001288 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001289 compileflags, 1) in test.globs
1290 exception = None
1291 except KeyboardInterrupt:
1292 raise
1293 except:
1294 exception = sys.exc_info()
1295
Tim Peters208ca702004-08-09 04:12:36 +00001296 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001297 self._fakeout.truncate(0)
1298
1299 # If the example executed without raising any exceptions,
1300 # then verify its output and report its outcome.
1301 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001302 if self._checker.check_output(example.want, got,
1303 self.optionflags):
Edward Lopera89f88d2004-08-26 02:45:51 +00001304 if not quiet:
1305 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001306 else:
Edward Lopera89f88d2004-08-26 02:45:51 +00001307 if not quiet:
1308 self.report_failure(out, test, example, got)
Tim Peters8485b562004-08-04 18:46:34 +00001309 failures += 1
1310
1311 # If the example raised an exception, then check if it was
1312 # expected.
1313 else:
1314 exc_info = sys.exc_info()
1315 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1316
Edward Lopera6b68322004-08-26 00:05:43 +00001317 # If `example.exc_msg` is None, then we weren't
1318 # expecting an exception.
1319 if example.exc_msg is None:
Edward Lopera89f88d2004-08-26 02:45:51 +00001320 if not quiet:
1321 self.report_unexpected_exception(out, test, example,
1322 exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001323 failures += 1
Edward Lopera6b68322004-08-26 00:05:43 +00001324 # If `example.exc_msg` matches the actual exception
1325 # message (`exc_msg`), then the example succeeds.
1326 elif (self._checker.check_output(example.exc_msg, exc_msg,
1327 self.optionflags)):
Edward Lopera89f88d2004-08-26 02:45:51 +00001328 if not quiet:
1329 got += _exception_traceback(exc_info)
1330 self.report_success(out, test, example, got)
Edward Lopera6b68322004-08-26 00:05:43 +00001331 # Otherwise, the example fails.
Tim Peters8485b562004-08-04 18:46:34 +00001332 else:
Edward Lopera89f88d2004-08-26 02:45:51 +00001333 if not quiet:
1334 got += _exception_traceback(exc_info)
1335 self.report_failure(out, test, example, got)
Edward Lopera6b68322004-08-26 00:05:43 +00001336 failures += 1
Tim Peters8485b562004-08-04 18:46:34 +00001337
1338 # Restore the option flags (in case they were modified)
1339 self.optionflags = original_optionflags
1340
1341 # Record and return the number of failures and tries.
1342 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001343 return failures, tries
1344
Tim Peters8485b562004-08-04 18:46:34 +00001345 def __record_outcome(self, test, f, t):
1346 """
1347 Record the fact that the given DocTest (`test`) generated `f`
1348 failures out of `t` tried examples.
1349 """
1350 f2, t2 = self._name2ft.get(test.name, (0,0))
1351 self._name2ft[test.name] = (f+f2, t+t2)
1352 self.failures += f
1353 self.tries += t
1354
1355 def run(self, test, compileflags=None, out=None, clear_globs=True):
1356 """
1357 Run the examples in `test`, and display the results using the
1358 writer function `out`.
1359
1360 The examples are run in the namespace `test.globs`. If
1361 `clear_globs` is true (the default), then this namespace will
1362 be cleared after the test runs, to help with garbage
1363 collection. If you would like to examine the namespace after
1364 the test completes, then use `clear_globs=False`.
1365
1366 `compileflags` gives the set of flags that should be used by
1367 the Python compiler when running the examples. If not
1368 specified, then it will default to the set of future-import
1369 flags that apply to `globs`.
1370
1371 The output of each example is checked using
1372 `DocTestRunner.check_output`, and the results are formatted by
1373 the `DocTestRunner.report_*` methods.
1374 """
1375 if compileflags is None:
1376 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001377
Tim Peters6c542b72004-08-09 16:43:36 +00001378 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001379 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001380 out = save_stdout.write
1381 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001382
Tim Peters6c542b72004-08-09 16:43:36 +00001383 # Patch pdb.set_trace to restore sys.stdout, so that interactive
1384 # debugging output is visible (not still redirected to self._fakeout).
1385 # Note that we run "the real" pdb.set_trace (captured at doctest
1386 # import time) in our replacement. Because the current run() may
1387 # run another doctest (and so on), the current pdb.set_trace may be
1388 # our set_trace function, which changes sys.stdout. If we called
1389 # a chain of those, we wouldn't be left with the save_stdout
1390 # *this* run() invocation wants.
Jim Fulton356fd192004-08-09 11:34:47 +00001391 def set_trace():
Tim Peters6c542b72004-08-09 16:43:36 +00001392 sys.stdout = save_stdout
Jim Fulton356fd192004-08-09 11:34:47 +00001393 real_pdb_set_trace()
1394
Tim Peters6c542b72004-08-09 16:43:36 +00001395 save_set_trace = pdb.set_trace
1396 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001397 try:
Tim Peters8485b562004-08-04 18:46:34 +00001398 return self.__run(test, compileflags, out)
1399 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001400 sys.stdout = save_stdout
1401 pdb.set_trace = save_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001402 if clear_globs:
1403 test.globs.clear()
1404
1405 #/////////////////////////////////////////////////////////////////
1406 # Summarization
1407 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001408 def summarize(self, verbose=None):
1409 """
Tim Peters8485b562004-08-04 18:46:34 +00001410 Print a summary of all the test cases that have been run by
1411 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1412 the total number of failed examples, and `t` is the total
1413 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001414
Tim Peters8485b562004-08-04 18:46:34 +00001415 The optional `verbose` argument controls how detailed the
1416 summary is. If the verbosity is not specified, then the
1417 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001418 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001419 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001420 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001421 notests = []
1422 passed = []
1423 failed = []
1424 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001425 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001426 name, (f, t) = x
1427 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001428 totalt += t
1429 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001430 if t == 0:
1431 notests.append(name)
1432 elif f == 0:
1433 passed.append( (name, t) )
1434 else:
1435 failed.append(x)
1436 if verbose:
1437 if notests:
1438 print len(notests), "items had no tests:"
1439 notests.sort()
1440 for thing in notests:
1441 print " ", thing
1442 if passed:
1443 print len(passed), "items passed all tests:"
1444 passed.sort()
1445 for thing, count in passed:
1446 print " %3d tests in %s" % (count, thing)
1447 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001448 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001449 print len(failed), "items had failures:"
1450 failed.sort()
1451 for thing, (f, t) in failed:
1452 print " %3d of %3d in %s" % (f, t, thing)
1453 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001454 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001455 print totalt - totalf, "passed and", totalf, "failed."
1456 if totalf:
1457 print "***Test Failed***", totalf, "failures."
1458 elif verbose:
1459 print "Test passed."
1460 return totalf, totalt
1461
Edward Loper34fcb142004-08-09 02:45:41 +00001462class OutputChecker:
1463 """
1464 A class used to check the whether the actual output from a doctest
1465 example matches the expected output. `OutputChecker` defines two
1466 methods: `check_output`, which compares a given pair of outputs,
1467 and returns true if they match; and `output_difference`, which
1468 returns a string describing the differences between two outputs.
1469 """
1470 def check_output(self, want, got, optionflags):
1471 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001472 Return True iff the actual output from an example (`got`)
1473 matches the expected output (`want`). These strings are
1474 always considered to match if they are identical; but
1475 depending on what option flags the test runner is using,
1476 several non-exact match types are also possible. See the
1477 documentation for `TestRunner` for more information about
1478 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001479 """
1480 # Handle the common case first, for efficiency:
1481 # if they're string-identical, always return true.
1482 if got == want:
1483 return True
1484
1485 # The values True and False replaced 1 and 0 as the return
1486 # value for boolean comparisons in Python 2.3.
1487 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1488 if (got,want) == ("True\n", "1\n"):
1489 return True
1490 if (got,want) == ("False\n", "0\n"):
1491 return True
1492
1493 # <BLANKLINE> can be used as a special sequence to signify a
1494 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1495 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1496 # Replace <BLANKLINE> in want with a blank line.
1497 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1498 '', want)
1499 # If a line in got contains only spaces, then remove the
1500 # spaces.
1501 got = re.sub('(?m)^\s*?$', '', got)
1502 if got == want:
1503 return True
1504
1505 # This flag causes doctest to ignore any differences in the
1506 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001507 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001508 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001509 got = ' '.join(got.split())
1510 want = ' '.join(want.split())
1511 if got == want:
1512 return True
1513
1514 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001515 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001516 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001517 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001518 return True
1519
1520 # We didn't find any match; return false.
1521 return False
1522
Tim Petersc6cbab02004-08-22 19:43:28 +00001523 # Should we do a fancy diff?
1524 def _do_a_fancy_diff(self, want, got, optionflags):
1525 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001526 if not optionflags & (REPORT_UDIFF |
1527 REPORT_CDIFF |
1528 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001529 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001530
Tim Petersc6cbab02004-08-22 19:43:28 +00001531 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001532 # too hard ... or maybe not. In two real-life failures Tim saw,
1533 # a diff was a major help anyway, so this is commented out.
1534 # [todo] _ellipsis_match() knows which pieces do and don't match,
1535 # and could be the basis for a kick-ass diff in this case.
1536 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1537 ## return False
1538
Tim Petersc6cbab02004-08-22 19:43:28 +00001539 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001540 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001541 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001542 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001543
Tim Petersc6cbab02004-08-22 19:43:28 +00001544 # The other diff types need at least a few lines to be helpful.
1545 return want.count('\n') > 2 and got.count('\n') > 2
1546
Edward Loperca9111e2004-08-26 03:00:24 +00001547 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001548 """
1549 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001550 expected output for a given example (`example`) and the actual
1551 output (`got`). `optionflags` is the set of option flags used
1552 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001553 """
Edward Loperca9111e2004-08-26 03:00:24 +00001554 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001555 # If <BLANKLINE>s are being used, then replace blank lines
1556 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001557 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001558 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001559
Tim Peters5b799c12004-08-26 05:21:59 +00001560 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001561 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001562 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001563 want_lines = want.splitlines(True) # True == keep line ends
1564 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001565 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001566 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001567 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1568 diff = list(diff)[2:] # strip the diff header
1569 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001570 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001571 diff = difflib.context_diff(want_lines, got_lines, n=2)
1572 diff = list(diff)[2:] # strip the diff header
1573 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001574 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001575 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1576 diff = list(engine.compare(want_lines, got_lines))
1577 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001578 else:
1579 assert 0, 'Bad diff option'
1580 # Remove trailing whitespace on diff output.
1581 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001582 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001583
1584 # If we're not using diff, then simply list the expected
1585 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001586 if want and got:
1587 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1588 elif want:
1589 return 'Expected:\n%sGot nothing\n' % _indent(want)
1590 elif got:
1591 return 'Expected nothing\nGot:\n%s' % _indent(got)
1592 else:
1593 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001594
Tim Peters19397e52004-08-06 22:02:59 +00001595class DocTestFailure(Exception):
1596 """A DocTest example has failed in debugging mode.
1597
1598 The exception instance has variables:
1599
1600 - test: the DocTest object being run
1601
1602 - excample: the Example object that failed
1603
1604 - got: the actual output
1605 """
1606 def __init__(self, test, example, got):
1607 self.test = test
1608 self.example = example
1609 self.got = got
1610
1611 def __str__(self):
1612 return str(self.test)
1613
1614class UnexpectedException(Exception):
1615 """A DocTest example has encountered an unexpected exception
1616
1617 The exception instance has variables:
1618
1619 - test: the DocTest object being run
1620
1621 - excample: the Example object that failed
1622
1623 - exc_info: the exception info
1624 """
1625 def __init__(self, test, example, exc_info):
1626 self.test = test
1627 self.example = example
1628 self.exc_info = exc_info
1629
1630 def __str__(self):
1631 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001632
Tim Peters19397e52004-08-06 22:02:59 +00001633class DebugRunner(DocTestRunner):
1634 r"""Run doc tests but raise an exception as soon as there is a failure.
1635
1636 If an unexpected exception occurs, an UnexpectedException is raised.
1637 It contains the test, the example, and the original exception:
1638
1639 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001640 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1641 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001642 >>> try:
1643 ... runner.run(test)
1644 ... except UnexpectedException, failure:
1645 ... pass
1646
1647 >>> failure.test is test
1648 True
1649
1650 >>> failure.example.want
1651 '42\n'
1652
1653 >>> exc_info = failure.exc_info
1654 >>> raise exc_info[0], exc_info[1], exc_info[2]
1655 Traceback (most recent call last):
1656 ...
1657 KeyError
1658
1659 We wrap the original exception to give the calling application
1660 access to the test and example information.
1661
1662 If the output doesn't match, then a DocTestFailure is raised:
1663
Edward Lopera1ef6112004-08-09 16:14:41 +00001664 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001665 ... >>> x = 1
1666 ... >>> x
1667 ... 2
1668 ... ''', {}, 'foo', 'foo.py', 0)
1669
1670 >>> try:
1671 ... runner.run(test)
1672 ... except DocTestFailure, failure:
1673 ... pass
1674
1675 DocTestFailure objects provide access to the test:
1676
1677 >>> failure.test is test
1678 True
1679
1680 As well as to the example:
1681
1682 >>> failure.example.want
1683 '2\n'
1684
1685 and the actual output:
1686
1687 >>> failure.got
1688 '1\n'
1689
1690 If a failure or error occurs, the globals are left intact:
1691
1692 >>> del test.globs['__builtins__']
1693 >>> test.globs
1694 {'x': 1}
1695
Edward Lopera1ef6112004-08-09 16:14:41 +00001696 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001697 ... >>> x = 2
1698 ... >>> raise KeyError
1699 ... ''', {}, 'foo', 'foo.py', 0)
1700
1701 >>> runner.run(test)
1702 Traceback (most recent call last):
1703 ...
1704 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001705
Tim Peters19397e52004-08-06 22:02:59 +00001706 >>> del test.globs['__builtins__']
1707 >>> test.globs
1708 {'x': 2}
1709
1710 But the globals are cleared if there is no error:
1711
Edward Lopera1ef6112004-08-09 16:14:41 +00001712 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001713 ... >>> x = 2
1714 ... ''', {}, 'foo', 'foo.py', 0)
1715
1716 >>> runner.run(test)
1717 (0, 1)
1718
1719 >>> test.globs
1720 {}
1721
1722 """
1723
1724 def run(self, test, compileflags=None, out=None, clear_globs=True):
1725 r = DocTestRunner.run(self, test, compileflags, out, False)
1726 if clear_globs:
1727 test.globs.clear()
1728 return r
1729
1730 def report_unexpected_exception(self, out, test, example, exc_info):
1731 raise UnexpectedException(test, example, exc_info)
1732
1733 def report_failure(self, out, test, example, got):
1734 raise DocTestFailure(test, example, got)
1735
Tim Peters8485b562004-08-04 18:46:34 +00001736######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001737## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001738######################################################################
1739# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001740
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001741def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001742 report=True, optionflags=0, extraglobs=None,
1743 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001744 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001745 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001746
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001747 Test examples in docstrings in functions and classes reachable
1748 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001749 with m.__doc__. Unless isprivate is specified, private names
1750 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001751
1752 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001753 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001754 function and class docstrings are tested even if the name is private;
1755 strings are tested directly, as if they were docstrings.
1756
1757 Return (#failures, #tests).
1758
1759 See doctest.__doc__ for an overview.
1760
1761 Optional keyword arg "name" gives the name of the module; by default
1762 use m.__name__.
1763
1764 Optional keyword arg "globs" gives a dict to be used as the globals
1765 when executing examples; by default, use m.__dict__. A copy of this
1766 dict is actually used for each docstring, so that each docstring's
1767 examples start with a clean slate.
1768
Tim Peters8485b562004-08-04 18:46:34 +00001769 Optional keyword arg "extraglobs" gives a dictionary that should be
1770 merged into the globals that are used to execute examples. By
1771 default, no extra globals are used. This is new in 2.4.
1772
Tim Peters8a7d2d52001-01-16 07:10:57 +00001773 Optional keyword arg "verbose" prints lots of stuff if true, prints
1774 only failures if false; by default, it's true iff "-v" is in sys.argv.
1775
Tim Peters8a7d2d52001-01-16 07:10:57 +00001776 Optional keyword arg "report" prints a summary at the end when true,
1777 else prints nothing at the end. In verbose mode, the summary is
1778 detailed, else very brief (in fact, empty if all tests passed).
1779
Tim Peters6ebe61f2003-06-27 20:48:05 +00001780 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001781 and defaults to 0. This is new in 2.3. Possible values (see the
1782 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001783
1784 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001785 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001786 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001787 ELLIPSIS
Edward Loper71f55af2004-08-26 01:41:51 +00001788 REPORT_UDIFF
1789 REPORT_CDIFF
1790 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001791 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001792
1793 Optional keyword arg "raise_on_error" raises an exception on the
1794 first unexpected exception or failure. This allows failures to be
1795 post-mortem debugged.
1796
Tim Petersf727c6c2004-08-08 01:48:59 +00001797 Deprecated in Python 2.4:
1798 Optional keyword arg "isprivate" specifies a function used to
1799 determine whether a name is private. The default function is
1800 treat all functions as public. Optionally, "isprivate" can be
1801 set to doctest.is_private to skip over functions marked as private
1802 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001803 """
1804
1805 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001806 Advanced tomfoolery: testmod runs methods of a local instance of
1807 class doctest.Tester, then merges the results into (or creates)
1808 global Tester instance doctest.master. Methods of doctest.master
1809 can be called directly too, if you want to do something unusual.
1810 Passing report=0 to testmod is especially useful then, to delay
1811 displaying a summary. Invoke doctest.master.summarize(verbose)
1812 when you're done fiddling.
1813 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001814 if isprivate is not None:
1815 warnings.warn("the isprivate argument is deprecated; "
1816 "examine DocTestFinder.find() lists instead",
1817 DeprecationWarning)
1818
Tim Peters8485b562004-08-04 18:46:34 +00001819 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001820 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001821 # DWA - m will still be None if this wasn't invoked from the command
1822 # line, in which case the following TypeError is about as good an error
1823 # as we should expect
1824 m = sys.modules.get('__main__')
1825
Tim Peters8485b562004-08-04 18:46:34 +00001826 # Check that we were actually given a module.
1827 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001828 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001829
1830 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001831 if name is None:
1832 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001833
1834 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001835 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001836
1837 if raise_on_error:
1838 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1839 else:
1840 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1841
Tim Peters8485b562004-08-04 18:46:34 +00001842 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1843 runner.run(test)
1844
Tim Peters8a7d2d52001-01-16 07:10:57 +00001845 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001846 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001847
Tim Peters8485b562004-08-04 18:46:34 +00001848 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001849
Tim Peters8485b562004-08-04 18:46:34 +00001850def run_docstring_examples(f, globs, verbose=False, name="NoName",
1851 compileflags=None, optionflags=0):
1852 """
1853 Test examples in the given object's docstring (`f`), using `globs`
1854 as globals. Optional argument `name` is used in failure messages.
1855 If the optional argument `verbose` is true, then generate output
1856 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001857
Tim Peters8485b562004-08-04 18:46:34 +00001858 `compileflags` gives the set of flags that should be used by the
1859 Python compiler when running the examples. If not specified, then
1860 it will default to the set of future-import flags that apply to
1861 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001862
Tim Peters8485b562004-08-04 18:46:34 +00001863 Optional keyword arg `optionflags` specifies options for the
1864 testing and output. See the documentation for `testmod` for more
1865 information.
1866 """
1867 # Find, parse, and run all tests in the given module.
1868 finder = DocTestFinder(verbose=verbose, recurse=False)
1869 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1870 for test in finder.find(f, name, globs=globs):
1871 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001872
Tim Peters8485b562004-08-04 18:46:34 +00001873######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001874## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001875######################################################################
1876# This is provided only for backwards compatibility. It's not
1877# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001878
Tim Peters8485b562004-08-04 18:46:34 +00001879class Tester:
1880 def __init__(self, mod=None, globs=None, verbose=None,
1881 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001882
1883 warnings.warn("class Tester is deprecated; "
1884 "use class doctest.DocTestRunner instead",
1885 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001886 if mod is None and globs is None:
1887 raise TypeError("Tester.__init__: must specify mod or globs")
1888 if mod is not None and not _ismodule(mod):
1889 raise TypeError("Tester.__init__: mod must be a module; %r" %
1890 (mod,))
1891 if globs is None:
1892 globs = mod.__dict__
1893 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001894
Tim Peters8485b562004-08-04 18:46:34 +00001895 self.verbose = verbose
1896 self.isprivate = isprivate
1897 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001898 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001899 self.testrunner = DocTestRunner(verbose=verbose,
1900 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001901
Tim Peters8485b562004-08-04 18:46:34 +00001902 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001903 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001904 if self.verbose:
1905 print "Running string", name
1906 (f,t) = self.testrunner.run(test)
1907 if self.verbose:
1908 print f, "of", t, "examples failed in string", name
1909 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001910
Tim Petersf3f57472004-08-08 06:11:48 +00001911 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001912 f = t = 0
1913 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001914 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001915 for test in tests:
1916 (f2, t2) = self.testrunner.run(test)
1917 (f,t) = (f+f2, t+t2)
1918 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001919
Tim Peters8485b562004-08-04 18:46:34 +00001920 def rundict(self, d, name, module=None):
1921 import new
1922 m = new.module(name)
1923 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001924 if module is None:
1925 module = False
1926 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001927
Tim Peters8485b562004-08-04 18:46:34 +00001928 def run__test__(self, d, name):
1929 import new
1930 m = new.module(name)
1931 m.__test__ = d
1932 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001933
Tim Peters8485b562004-08-04 18:46:34 +00001934 def summarize(self, verbose=None):
1935 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001936
Tim Peters8485b562004-08-04 18:46:34 +00001937 def merge(self, other):
1938 d = self.testrunner._name2ft
1939 for name, (f, t) in other.testrunner._name2ft.items():
1940 if name in d:
1941 print "*** Tester.merge: '" + name + "' in both" \
1942 " testers; summing outcomes."
1943 f2, t2 = d[name]
1944 f = f + f2
1945 t = t + t2
1946 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001947
Tim Peters8485b562004-08-04 18:46:34 +00001948######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001949## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001950######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001951
Tim Peters19397e52004-08-06 22:02:59 +00001952class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001953
Edward Loper34fcb142004-08-09 02:45:41 +00001954 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
1955 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00001956
Jim Fultona643b652004-07-14 19:06:50 +00001957 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00001958 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00001959 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00001960 self._dt_test = test
1961 self._dt_setUp = setUp
1962 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00001963
Jim Fultona643b652004-07-14 19:06:50 +00001964 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00001965 if self._dt_setUp is not None:
1966 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00001967
1968 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00001969 if self._dt_tearDown is not None:
1970 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00001971
1972 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00001973 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00001974 old = sys.stdout
1975 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00001976 runner = DocTestRunner(optionflags=self._dt_optionflags,
1977 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001978
Jim Fultona643b652004-07-14 19:06:50 +00001979 try:
Tim Peters19397e52004-08-06 22:02:59 +00001980 runner.DIVIDER = "-"*70
1981 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00001982 finally:
1983 sys.stdout = old
1984
1985 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00001986 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00001987
Tim Peters19397e52004-08-06 22:02:59 +00001988 def format_failure(self, err):
1989 test = self._dt_test
1990 if test.lineno is None:
1991 lineno = 'unknown line number'
1992 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001993 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00001994 lname = '.'.join(test.name.split('.')[-1:])
1995 return ('Failed doctest test for %s\n'
1996 ' File "%s", line %s, in %s\n\n%s'
1997 % (test.name, test.filename, lineno, lname, err)
1998 )
1999
2000 def debug(self):
2001 r"""Run the test case without results and without catching exceptions
2002
2003 The unit test framework includes a debug method on test cases
2004 and test suites to support post-mortem debugging. The test code
2005 is run in such a way that errors are not caught. This way a
2006 caller can catch the errors and initiate post-mortem debugging.
2007
2008 The DocTestCase provides a debug method that raises
2009 UnexpectedException errors if there is an unexepcted
2010 exception:
2011
Edward Lopera1ef6112004-08-09 16:14:41 +00002012 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002013 ... {}, 'foo', 'foo.py', 0)
2014 >>> case = DocTestCase(test)
2015 >>> try:
2016 ... case.debug()
2017 ... except UnexpectedException, failure:
2018 ... pass
2019
2020 The UnexpectedException contains the test, the example, and
2021 the original exception:
2022
2023 >>> failure.test is test
2024 True
2025
2026 >>> failure.example.want
2027 '42\n'
2028
2029 >>> exc_info = failure.exc_info
2030 >>> raise exc_info[0], exc_info[1], exc_info[2]
2031 Traceback (most recent call last):
2032 ...
2033 KeyError
2034
2035 If the output doesn't match, then a DocTestFailure is raised:
2036
Edward Lopera1ef6112004-08-09 16:14:41 +00002037 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002038 ... >>> x = 1
2039 ... >>> x
2040 ... 2
2041 ... ''', {}, 'foo', 'foo.py', 0)
2042 >>> case = DocTestCase(test)
2043
2044 >>> try:
2045 ... case.debug()
2046 ... except DocTestFailure, failure:
2047 ... pass
2048
2049 DocTestFailure objects provide access to the test:
2050
2051 >>> failure.test is test
2052 True
2053
2054 As well as to the example:
2055
2056 >>> failure.example.want
2057 '2\n'
2058
2059 and the actual output:
2060
2061 >>> failure.got
2062 '1\n'
2063
2064 """
2065
Edward Loper34fcb142004-08-09 02:45:41 +00002066 runner = DebugRunner(optionflags=self._dt_optionflags,
2067 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002068 runner.run(self._dt_test)
Jim Fultona643b652004-07-14 19:06:50 +00002069
2070 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002071 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002072
2073 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002074 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002075 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2076
2077 __str__ = __repr__
2078
2079 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002080 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002081
Tim Peters19397e52004-08-06 22:02:59 +00002082def DocTestSuite(module=None, globs=None, extraglobs=None,
2083 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002084 setUp=lambda: None, tearDown=lambda: None,
2085 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002086 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002087 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002088
Tim Peters19397e52004-08-06 22:02:59 +00002089 This converts each documentation string in a module that
2090 contains doctest tests to a unittest test case. If any of the
2091 tests in a doc string fail, then the test case fails. An exception
2092 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002093 (sometimes approximate) line number.
2094
Tim Peters19397e52004-08-06 22:02:59 +00002095 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002096 can be either a module or a module name.
2097
2098 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002099 """
Jim Fultona643b652004-07-14 19:06:50 +00002100
Tim Peters8485b562004-08-04 18:46:34 +00002101 if test_finder is None:
2102 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002103
Tim Peters19397e52004-08-06 22:02:59 +00002104 module = _normalize_module(module)
2105 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2106 if globs is None:
2107 globs = module.__dict__
2108 if not tests: # [XX] why do we want to do this?
2109 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002110
2111 tests.sort()
2112 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002113 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002114 if len(test.examples) == 0:
2115 continue
Tim Peters8485b562004-08-04 18:46:34 +00002116 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002117 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002118 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002119 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002120 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002121 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2122 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002123
2124 return suite
2125
2126class DocFileCase(DocTestCase):
2127
2128 def id(self):
2129 return '_'.join(self._dt_test.name.split('.'))
2130
2131 def __repr__(self):
2132 return self._dt_test.filename
2133 __str__ = __repr__
2134
2135 def format_failure(self, err):
2136 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2137 % (self._dt_test.name, self._dt_test.filename, err)
2138 )
2139
2140def DocFileTest(path, package=None, globs=None,
2141 setUp=None, tearDown=None,
2142 optionflags=0):
2143 package = _normalize_module(package)
2144 name = path.split('/')[-1]
2145 dir = os.path.split(package.__file__)[0]
2146 path = os.path.join(dir, *(path.split('/')))
2147 doc = open(path).read()
2148
2149 if globs is None:
2150 globs = {}
2151
Edward Lopera1ef6112004-08-09 16:14:41 +00002152 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002153
2154 return DocFileCase(test, optionflags, setUp, tearDown)
2155
2156def DocFileSuite(*paths, **kw):
2157 """Creates a suite of doctest files.
2158
2159 One or more text file paths are given as strings. These should
2160 use "/" characters to separate path segments. Paths are relative
2161 to the directory of the calling module, or relative to the package
2162 passed as a keyword argument.
2163
2164 A number of options may be provided as keyword arguments:
2165
2166 package
2167 The name of a Python package. Text-file paths will be
2168 interpreted relative to the directory containing this package.
2169 The package may be supplied as a package object or as a dotted
2170 package name.
2171
2172 setUp
2173 The name of a set-up function. This is called before running the
2174 tests in each file.
2175
2176 tearDown
2177 The name of a tear-down function. This is called after running the
2178 tests in each file.
2179
2180 globs
2181 A dictionary containing initial global variables for the tests.
2182 """
2183 suite = unittest.TestSuite()
2184
2185 # We do this here so that _normalize_module is called at the right
2186 # level. If it were called in DocFileTest, then this function
2187 # would be the caller and we might guess the package incorrectly.
2188 kw['package'] = _normalize_module(kw.get('package'))
2189
2190 for path in paths:
2191 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002192
Tim Petersdb3756d2003-06-29 05:30:48 +00002193 return suite
2194
Tim Peters8485b562004-08-04 18:46:34 +00002195######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002196## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002197######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002198
Tim Peters19397e52004-08-06 22:02:59 +00002199def script_from_examples(s):
2200 r"""Extract script from text with examples.
2201
2202 Converts text with examples to a Python script. Example input is
2203 converted to regular code. Example output and all other words
2204 are converted to comments:
2205
2206 >>> text = '''
2207 ... Here are examples of simple math.
2208 ...
2209 ... Python has super accurate integer addition
2210 ...
2211 ... >>> 2 + 2
2212 ... 5
2213 ...
2214 ... And very friendly error messages:
2215 ...
2216 ... >>> 1/0
2217 ... To Infinity
2218 ... And
2219 ... Beyond
2220 ...
2221 ... You can use logic if you want:
2222 ...
2223 ... >>> if 0:
2224 ... ... blah
2225 ... ... blah
2226 ... ...
2227 ...
2228 ... Ho hum
2229 ... '''
2230
2231 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002232 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002233 #
Edward Lopera5db6002004-08-12 02:41:30 +00002234 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002235 #
2236 2 + 2
2237 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002238 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002239 #
Edward Lopera5db6002004-08-12 02:41:30 +00002240 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002241 #
2242 1/0
2243 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002244 ## To Infinity
2245 ## And
2246 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002247 #
Edward Lopera5db6002004-08-12 02:41:30 +00002248 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002249 #
2250 if 0:
2251 blah
2252 blah
Tim Peters19397e52004-08-06 22:02:59 +00002253 #
Edward Lopera5db6002004-08-12 02:41:30 +00002254 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002255 """
Edward Loper00f8da72004-08-26 18:05:07 +00002256 output = []
2257 for piece in DocTestParser().parse(s):
2258 if isinstance(piece, Example):
2259 # Add the example's source code (strip trailing NL)
2260 output.append(piece.source[:-1])
2261 # Add the expected output:
2262 want = piece.want
2263 if want:
2264 output.append('# Expected:')
2265 output += ['## '+l for l in want.split('\n')[:-1]]
2266 else:
2267 # Add non-example text.
2268 output += [_comment_line(l)
2269 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002270
Edward Loper00f8da72004-08-26 18:05:07 +00002271 # Trim junk on both ends.
2272 while output and output[-1] == '#':
2273 output.pop()
2274 while output and output[0] == '#':
2275 output.pop(0)
2276 # Combine the output, and return it.
2277 return '\n'.join(output)
Tim Petersdb3756d2003-06-29 05:30:48 +00002278
2279def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002280 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002281
2282 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002283 test to be debugged and the name (within the module) of the object
2284 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002285 """
Tim Peters8485b562004-08-04 18:46:34 +00002286 module = _normalize_module(module)
2287 tests = DocTestFinder().find(module)
2288 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002289 if not test:
2290 raise ValueError(name, "not found in tests")
2291 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002292 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002293 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002294
Jim Fultona643b652004-07-14 19:06:50 +00002295def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002296 """Debug a single doctest docstring, in argument `src`'"""
2297 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002298 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002299
Jim Fultona643b652004-07-14 19:06:50 +00002300def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002301 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002302 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002303
Tim Petersb6a04d62004-08-23 21:37:56 +00002304 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2305 # docs say, a file so created cannot be opened by name a second time
2306 # on modern Windows boxes, and execfile() needs to open it.
2307 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002308 f = open(srcfilename, 'w')
2309 f.write(src)
2310 f.close()
2311
Tim Petersb6a04d62004-08-23 21:37:56 +00002312 try:
2313 if globs:
2314 globs = globs.copy()
2315 else:
2316 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002317
Tim Petersb6a04d62004-08-23 21:37:56 +00002318 if pm:
2319 try:
2320 execfile(srcfilename, globs, globs)
2321 except:
2322 print sys.exc_info()[1]
2323 pdb.post_mortem(sys.exc_info()[2])
2324 else:
2325 # Note that %r is vital here. '%s' instead can, e.g., cause
2326 # backslashes to get treated as metacharacters on Windows.
2327 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2328
2329 finally:
2330 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002331
Jim Fultona643b652004-07-14 19:06:50 +00002332def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002333 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002334
2335 Provide the module (or dotted name of the module) containing the
2336 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002337 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002338 """
Tim Peters8485b562004-08-04 18:46:34 +00002339 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002340 testsrc = testsource(module, name)
2341 debug_script(testsrc, pm, module.__dict__)
2342
Tim Peters8485b562004-08-04 18:46:34 +00002343######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002344## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002345######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002346class _TestClass:
2347 """
2348 A pointless class, for sanity-checking of docstring testing.
2349
2350 Methods:
2351 square()
2352 get()
2353
2354 >>> _TestClass(13).get() + _TestClass(-12).get()
2355 1
2356 >>> hex(_TestClass(13).square().get())
2357 '0xa9'
2358 """
2359
2360 def __init__(self, val):
2361 """val -> _TestClass object with associated value val.
2362
2363 >>> t = _TestClass(123)
2364 >>> print t.get()
2365 123
2366 """
2367
2368 self.val = val
2369
2370 def square(self):
2371 """square() -> square TestClass's associated value
2372
2373 >>> _TestClass(13).square().get()
2374 169
2375 """
2376
2377 self.val = self.val ** 2
2378 return self
2379
2380 def get(self):
2381 """get() -> return TestClass's associated value.
2382
2383 >>> x = _TestClass(-42)
2384 >>> print x.get()
2385 -42
2386 """
2387
2388 return self.val
2389
2390__test__ = {"_TestClass": _TestClass,
2391 "string": r"""
2392 Example of a string object, searched as-is.
2393 >>> x = 1; y = 2
2394 >>> x + y, x * y
2395 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002396 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002397
Tim Peters6ebe61f2003-06-27 20:48:05 +00002398 "bool-int equivalence": r"""
2399 In 2.2, boolean expressions displayed
2400 0 or 1. By default, we still accept
2401 them. This can be disabled by passing
2402 DONT_ACCEPT_TRUE_FOR_1 to the new
2403 optionflags argument.
2404 >>> 4 == 4
2405 1
2406 >>> 4 == 4
2407 True
2408 >>> 4 > 4
2409 0
2410 >>> 4 > 4
2411 False
2412 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002413
Tim Peters8485b562004-08-04 18:46:34 +00002414 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002415 Blank lines can be marked with <BLANKLINE>:
2416 >>> print 'foo\n\nbar\n'
2417 foo
2418 <BLANKLINE>
2419 bar
2420 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002421 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002422
2423 "ellipsis": r"""
2424 If the ellipsis flag is used, then '...' can be used to
2425 elide substrings in the desired output:
2426 >>> print range(1000) #doctest: +ELLIPSIS
2427 [0, 1, 2, ..., 999]
2428 """,
2429
2430 "whitespace normalization": r"""
2431 If the whitespace normalization flag is used, then
2432 differences in whitespace are ignored.
2433 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2434 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2435 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2436 27, 28, 29]
2437 """,
2438 }
Tim Peters8485b562004-08-04 18:46:34 +00002439
Tim Peters8a7d2d52001-01-16 07:10:57 +00002440def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002441 r = unittest.TextTestRunner()
2442 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002443
2444if __name__ == "__main__":
2445 _test()