blob: c27dd056a6f3ac5a941127e955d5ca25cfac17bf [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
Edward Loper2de91ba2004-08-27 02:07:46 +0000444class _OutputRedirectingPdb(pdb.Pdb):
445 """
446 A specialized version of the python debugger that redirects stdout
447 to a given stream when interacting with the user. Stdout is *not*
448 redirected when traced code is executed.
449 """
450 def __init__(self, out):
451 self.__out = out
452 pdb.Pdb.__init__(self)
453
454 def trace_dispatch(self, *args):
455 # Redirect stdout to the given stream.
456 save_stdout = sys.stdout
457 sys.stdout = self.__out
458 # Call Pdb's trace dispatch method.
459 pdb.Pdb.trace_dispatch(self, *args)
460 # Restore stdout.
461 sys.stdout = save_stdout
462
Tim Peters8485b562004-08-04 18:46:34 +0000463######################################################################
464## 2. Example & DocTest
465######################################################################
466## - An "example" is a <source, want> pair, where "source" is a
467## fragment of source code, and "want" is the expected output for
468## "source." The Example class also includes information about
469## where the example was extracted from.
470##
Edward Lopera1ef6112004-08-09 16:14:41 +0000471## - A "doctest" is a collection of examples, typically extracted from
472## a string (such as an object's docstring). The DocTest class also
473## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000474
Tim Peters8485b562004-08-04 18:46:34 +0000475class Example:
476 """
477 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000478 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000479
Edward Loper74bca7a2004-08-12 02:27:44 +0000480 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000481 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000482
Edward Loper74bca7a2004-08-12 02:27:44 +0000483 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000484 from stdout, or a traceback in case of exception). `want` ends
485 with a newline unless it's empty, in which case it's an empty
486 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000487
Edward Lopera6b68322004-08-26 00:05:43 +0000488 - exc_msg: The exception message generated by the example, if
489 the example is expected to generate an exception; or `None` if
490 it is not expected to generate an exception. This exception
491 message is compared against the return value of
492 `traceback.format_exception_only()`. `exc_msg` ends with a
493 newline unless it's `None`. The constructor adds a newline
494 if needed.
495
Edward Loper74bca7a2004-08-12 02:27:44 +0000496 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000497 this Example where the Example begins. This line number is
498 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000499
500 - indent: The example's indentation in the DocTest string.
501 I.e., the number of space characters that preceed the
502 example's first prompt.
503
504 - options: A dictionary mapping from option flags to True or
505 False, which is used to override default options for this
506 example. Any option flags not contained in this dictionary
507 are left at their default value (as specified by the
508 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000509 """
Edward Lopera6b68322004-08-26 00:05:43 +0000510 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
511 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000512 # Normalize inputs.
513 if not source.endswith('\n'):
514 source += '\n'
515 if want and not want.endswith('\n'):
516 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000517 if exc_msg is not None and not exc_msg.endswith('\n'):
518 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000519 # Store properties.
520 self.source = source
521 self.want = want
522 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000523 self.indent = indent
524 if options is None: options = {}
525 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000526 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000527
Tim Peters8485b562004-08-04 18:46:34 +0000528class DocTest:
529 """
530 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000531 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000532
Tim Peters8485b562004-08-04 18:46:34 +0000533 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000534
Tim Peters8485b562004-08-04 18:46:34 +0000535 - globs: The namespace (aka globals) that the examples should
536 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000537
Tim Peters8485b562004-08-04 18:46:34 +0000538 - name: A name identifying the DocTest (typically, the name of
539 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000540
Tim Peters8485b562004-08-04 18:46:34 +0000541 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000542 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000543
Tim Peters8485b562004-08-04 18:46:34 +0000544 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000545 begins, or `None` if the line number is unavailable. This
546 line number is zero-based, with respect to the beginning of
547 the file.
548
549 - docstring: The string that the examples were extracted from,
550 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000551 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000552 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000553 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000554 Create a new DocTest containing the given examples. The
555 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000556 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000557 assert not isinstance(examples, basestring), \
558 "DocTest no longer accepts str; use DocTestParser instead"
559 self.examples = examples
560 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000561 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000562 self.name = name
563 self.filename = filename
564 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000565
566 def __repr__(self):
567 if len(self.examples) == 0:
568 examples = 'no examples'
569 elif len(self.examples) == 1:
570 examples = '1 example'
571 else:
572 examples = '%d examples' % len(self.examples)
573 return ('<DocTest %s from %s:%s (%s)>' %
574 (self.name, self.filename, self.lineno, examples))
575
576
577 # This lets us sort tests by name:
578 def __cmp__(self, other):
579 if not isinstance(other, DocTest):
580 return -1
581 return cmp((self.name, self.filename, self.lineno, id(self)),
582 (other.name, other.filename, other.lineno, id(other)))
583
584######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000585## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000586######################################################################
587
Edward Lopera1ef6112004-08-09 16:14:41 +0000588class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000589 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000590 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000591 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000592 # This regular expression is used to find doctest examples in a
593 # string. It defines three groups: `source` is the source code
594 # (including leading indentation and prompts); `indent` is the
595 # indentation of the first (PS1) line of the source code; and
596 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000597 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000598 # Source consists of a PS1 line followed by zero or more PS2 lines.
599 (?P<source>
600 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
601 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
602 \n?
603 # Want consists of any non-blank lines that do not start with PS1.
604 (?P<want> (?:(?![ ]*$) # Not a blank line
605 (?![ ]*>>>) # Not a line starting with PS1
606 .*$\n? # But any other line
607 )*)
608 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000609
Edward Lopera6b68322004-08-26 00:05:43 +0000610 # A regular expression for handling `want` strings that contain
611 # expected exceptions. It divides `want` into three pieces:
612 # - the traceback header line (`hdr`)
613 # - the traceback stack (`stack`)
614 # - the exception message (`msg`), as generated by
615 # traceback.format_exception_only()
616 # `msg` may have multiple lines. We assume/require that the
617 # exception message is the first non-indented line starting with a word
618 # character following the traceback header line.
619 _EXCEPTION_RE = re.compile(r"""
620 # Grab the traceback header. Different versions of Python have
621 # said different things on the first traceback line.
622 ^(?P<hdr> Traceback\ \(
623 (?: most\ recent\ call\ last
624 | innermost\ last
625 ) \) :
626 )
627 \s* $ # toss trailing whitespace on the header.
628 (?P<stack> .*?) # don't blink: absorb stuff until...
629 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
630 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
631
Tim Peters7ea48dd2004-08-13 01:52:59 +0000632 # A callable returning a true value iff its argument is a blank line
633 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000634 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000635
Edward Loper00f8da72004-08-26 18:05:07 +0000636 def parse(self, string, name='<string>'):
637 """
638 Divide the given string into examples and intervening text,
639 and return them as a list of alternating Examples and strings.
640 Line numbers for the Examples are 0-based. The optional
641 argument `name` is a name identifying this string, and is only
642 used for error messages.
643 """
644 string = string.expandtabs()
645 # If all lines begin with the same indentation, then strip it.
646 min_indent = self._min_indent(string)
647 if min_indent > 0:
648 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
649
650 output = []
651 charno, lineno = 0, 0
652 # Find all doctest examples in the string:
Edward Loper2de91ba2004-08-27 02:07:46 +0000653 for m in self._EXAMPLE_RE.finditer(string):
Edward Loper00f8da72004-08-26 18:05:07 +0000654 # Add the pre-example text to `output`.
655 output.append(string[charno:m.start()])
656 # Update lineno (lines before this example)
657 lineno += string.count('\n', charno, m.start())
658 # Extract info from the regexp match.
659 (source, options, want, exc_msg) = \
660 self._parse_example(m, name, lineno)
661 # Create an Example, and add it to the list.
662 if not self._IS_BLANK_OR_COMMENT(source):
663 output.append( Example(source, want, exc_msg,
664 lineno=lineno,
665 indent=min_indent+len(m.group('indent')),
666 options=options) )
667 # Update lineno (lines inside this example)
668 lineno += string.count('\n', m.start(), m.end())
669 # Update charno.
670 charno = m.end()
671 # Add any remaining post-example text to `output`.
672 output.append(string[charno:])
673 return output
674
Edward Lopera1ef6112004-08-09 16:14:41 +0000675 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000676 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000677 Extract all doctest examples from the given string, and
678 collect them into a `DocTest` object.
679
680 `globs`, `name`, `filename`, and `lineno` are attributes for
681 the new `DocTest` object. See the documentation for `DocTest`
682 for more information.
683 """
684 return DocTest(self.get_examples(string, name), globs,
685 name, filename, lineno, string)
686
687 def get_examples(self, string, name='<string>'):
688 """
689 Extract all doctest examples from the given string, and return
690 them as a list of `Example` objects. Line numbers are
691 0-based, because it's most common in doctests that nothing
692 interesting appears on the same line as opening triple-quote,
693 and so the first interesting line is called \"line 1\" then.
694
695 The optional argument `name` is a name identifying this
696 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000697 """
Edward Loper00f8da72004-08-26 18:05:07 +0000698 return [x for x in self.parse(string, name)
699 if isinstance(x, Example)]
Edward Loper7c748462004-08-09 02:06:06 +0000700
Edward Loper74bca7a2004-08-12 02:27:44 +0000701 def _parse_example(self, m, name, lineno):
702 """
703 Given a regular expression match from `_EXAMPLE_RE` (`m`),
704 return a pair `(source, want)`, where `source` is the matched
705 example's source code (with prompts and indentation stripped);
706 and `want` is the example's expected output (with indentation
707 stripped).
708
709 `name` is the string's name, and `lineno` is the line number
710 where the example starts; both are used for error messages.
711 """
Edward Loper7c748462004-08-09 02:06:06 +0000712 # Get the example's indentation level.
713 indent = len(m.group('indent'))
714
715 # Divide source into lines; check that they're properly
716 # indented; and then strip their indentation & prompts.
717 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000718 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000719 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000720 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000721
Tim Petersc5049152004-08-22 17:34:58 +0000722 # Divide want into lines; check that it's properly indented; and
723 # then strip the indentation. Spaces before the last newline should
724 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000725 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000726 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000727 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
728 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000729 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000730 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000731 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000732
Edward Lopera6b68322004-08-26 00:05:43 +0000733 # If `want` contains a traceback message, then extract it.
734 m = self._EXCEPTION_RE.match(want)
735 if m:
736 exc_msg = m.group('msg')
737 else:
738 exc_msg = None
739
Edward Loper00f8da72004-08-26 18:05:07 +0000740 # Extract options from the source.
741 options = self._find_options(source, name, lineno)
742
743 return source, options, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000744
Edward Loper74bca7a2004-08-12 02:27:44 +0000745 # This regular expression looks for option directives in the
746 # source code of an example. Option directives are comments
747 # starting with "doctest:". Warning: this may give false
748 # positives for string-literals that contain the string
749 # "#doctest:". Eliminating these false positives would require
750 # actually parsing the string; but we limit them by ignoring any
751 # line containing "#doctest:" that is *followed* by a quote mark.
752 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
753 re.MULTILINE)
754
755 def _find_options(self, source, name, lineno):
756 """
757 Return a dictionary containing option overrides extracted from
758 option directives in the given source string.
759
760 `name` is the string's name, and `lineno` is the line number
761 where the example starts; both are used for error messages.
762 """
763 options = {}
764 # (note: with the current regexp, this will match at most once:)
765 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
766 option_strings = m.group(1).replace(',', ' ').split()
767 for option in option_strings:
768 if (option[0] not in '+-' or
769 option[1:] not in OPTIONFLAGS_BY_NAME):
770 raise ValueError('line %r of the doctest for %s '
771 'has an invalid option: %r' %
772 (lineno+1, name, option))
773 flag = OPTIONFLAGS_BY_NAME[option[1:]]
774 options[flag] = (option[0] == '+')
775 if options and self._IS_BLANK_OR_COMMENT(source):
776 raise ValueError('line %r of the doctest for %s has an option '
777 'directive on a line with no example: %r' %
778 (lineno, name, source))
779 return options
780
Edward Lopera5db6002004-08-12 02:41:30 +0000781 # This regular expression finds the indentation of every non-blank
782 # line in a string.
Edward Loper00f8da72004-08-26 18:05:07 +0000783 _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
Edward Lopera5db6002004-08-12 02:41:30 +0000784
785 def _min_indent(self, s):
786 "Return the minimum indentation of any non-blank line in `s`"
Edward Loper00f8da72004-08-26 18:05:07 +0000787 indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
788 if len(indents) > 0:
789 return min(indents)
Tim Petersdd0e4752004-08-09 03:31:56 +0000790 else:
Edward Loper00f8da72004-08-26 18:05:07 +0000791 return 0
Edward Loper7c748462004-08-09 02:06:06 +0000792
Edward Lopera1ef6112004-08-09 16:14:41 +0000793 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000794 """
795 Given the lines of a source string (including prompts and
796 leading indentation), check to make sure that every prompt is
797 followed by a space character. If any line is not followed by
798 a space character, then raise ValueError.
799 """
Edward Loper7c748462004-08-09 02:06:06 +0000800 for i, line in enumerate(lines):
801 if len(line) >= indent+4 and line[indent+3] != ' ':
802 raise ValueError('line %r of the docstring for %s '
803 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000804 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000805 line[indent:indent+3], line))
806
Edward Lopera1ef6112004-08-09 16:14:41 +0000807 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000808 """
809 Check that every line in the given list starts with the given
810 prefix; if any line does not, then raise a ValueError.
811 """
Edward Loper7c748462004-08-09 02:06:06 +0000812 for i, line in enumerate(lines):
813 if line and not line.startswith(prefix):
814 raise ValueError('line %r of the docstring for %s has '
815 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000816 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000817
818
819######################################################################
820## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000821######################################################################
822
823class DocTestFinder:
824 """
825 A class used to extract the DocTests that are relevant to a given
826 object, from its docstring and the docstrings of its contained
827 objects. Doctests can currently be extracted from the following
828 object types: modules, functions, classes, methods, staticmethods,
829 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000830 """
831
Edward Lopera1ef6112004-08-09 16:14:41 +0000832 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000833 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000834 """
835 Create a new doctest finder.
836
Edward Lopera1ef6112004-08-09 16:14:41 +0000837 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000838 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000839 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000840 signature for this factory function should match the signature
841 of the DocTest constructor.
842
Tim Peters8485b562004-08-04 18:46:34 +0000843 If the optional argument `recurse` is false, then `find` will
844 only examine the given object, and not any contained objects.
845 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000846 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000847 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000848 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000849 # _namefilter is undocumented, and exists only for temporary backward-
850 # compatibility support of testmod's deprecated isprivate mess.
851 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000852
853 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000854 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000855 """
856 Return a list of the DocTests that are defined by the given
857 object's docstring, or by any of its contained objects'
858 docstrings.
859
860 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000861 the given object. If the module is not specified or is None, then
862 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000863 correct module. The object's module is used:
864
865 - As a default namespace, if `globs` is not specified.
866 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000867 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000868 - To find the name of the file containing the object.
869 - To help find the line number of the object within its
870 file.
871
Tim Petersf3f57472004-08-08 06:11:48 +0000872 Contained objects whose module does not match `module` are ignored.
873
874 If `module` is False, no attempt to find the module will be made.
875 This is obscure, of use mostly in tests: if `module` is False, or
876 is None but cannot be found automatically, then all objects are
877 considered to belong to the (non-existent) module, so all contained
878 objects will (recursively) be searched for doctests.
879
Tim Peters8485b562004-08-04 18:46:34 +0000880 The globals for each DocTest is formed by combining `globs`
881 and `extraglobs` (bindings in `extraglobs` override bindings
882 in `globs`). A new copy of the globals dictionary is created
883 for each DocTest. If `globs` is not specified, then it
884 defaults to the module's `__dict__`, if specified, or {}
885 otherwise. If `extraglobs` is not specified, then it defaults
886 to {}.
887
Tim Peters8485b562004-08-04 18:46:34 +0000888 """
889 # If name was not specified, then extract it from the object.
890 if name is None:
891 name = getattr(obj, '__name__', None)
892 if name is None:
893 raise ValueError("DocTestFinder.find: name must be given "
894 "when obj.__name__ doesn't exist: %r" %
895 (type(obj),))
896
897 # Find the module that contains the given object (if obj is
898 # a module, then module=obj.). Note: this may fail, in which
899 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000900 if module is False:
901 module = None
902 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000903 module = inspect.getmodule(obj)
904
905 # Read the module's source code. This is used by
906 # DocTestFinder._find_lineno to find the line number for a
907 # given object's docstring.
908 try:
909 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
910 source_lines = linecache.getlines(file)
911 if not source_lines:
912 source_lines = None
913 except TypeError:
914 source_lines = None
915
916 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000917 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000918 if module is None:
919 globs = {}
920 else:
921 globs = module.__dict__.copy()
922 else:
923 globs = globs.copy()
924 if extraglobs is not None:
925 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000926
Tim Peters8485b562004-08-04 18:46:34 +0000927 # Recursively expore `obj`, extracting DocTests.
928 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000929 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000930 return tests
931
932 def _filter(self, obj, prefix, base):
933 """
934 Return true if the given object should not be examined.
935 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000936 return (self._namefilter is not None and
937 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000938
939 def _from_module(self, module, object):
940 """
941 Return true if the given object is defined in the given
942 module.
943 """
944 if module is None:
945 return True
946 elif inspect.isfunction(object):
947 return module.__dict__ is object.func_globals
948 elif inspect.isclass(object):
949 return module.__name__ == object.__module__
950 elif inspect.getmodule(object) is not None:
951 return module is inspect.getmodule(object)
952 elif hasattr(object, '__module__'):
953 return module.__name__ == object.__module__
954 elif isinstance(object, property):
955 return True # [XX] no way not be sure.
956 else:
957 raise ValueError("object must be a class or function")
958
Tim Petersf3f57472004-08-08 06:11:48 +0000959 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000960 """
961 Find tests for the given object and any contained objects, and
962 add them to `tests`.
963 """
964 if self._verbose:
965 print 'Finding tests in %s' % name
966
967 # If we've already processed this object, then ignore it.
968 if id(obj) in seen:
969 return
970 seen[id(obj)] = 1
971
972 # Find a test for this object, and add it to the list of tests.
973 test = self._get_test(obj, name, module, globs, source_lines)
974 if test is not None:
975 tests.append(test)
976
977 # Look for tests in a module's contained objects.
978 if inspect.ismodule(obj) and self._recurse:
979 for valname, val in obj.__dict__.items():
980 # Check if this contained object should be ignored.
981 if self._filter(val, name, valname):
982 continue
983 valname = '%s.%s' % (name, valname)
984 # Recurse to functions & classes.
985 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000986 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000987 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000988 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000989
990 # Look for tests in a module's __test__ dictionary.
991 if inspect.ismodule(obj) and self._recurse:
992 for valname, val in getattr(obj, '__test__', {}).items():
993 if not isinstance(valname, basestring):
994 raise ValueError("DocTestFinder.find: __test__ keys "
995 "must be strings: %r" %
996 (type(valname),))
997 if not (inspect.isfunction(val) or inspect.isclass(val) or
998 inspect.ismethod(val) or inspect.ismodule(val) or
999 isinstance(val, basestring)):
1000 raise ValueError("DocTestFinder.find: __test__ values "
1001 "must be strings, functions, methods, "
1002 "classes, or modules: %r" %
1003 (type(val),))
1004 valname = '%s.%s' % (name, valname)
1005 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001006 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001007
1008 # Look for tests in a class's contained objects.
1009 if inspect.isclass(obj) and self._recurse:
1010 for valname, val in obj.__dict__.items():
1011 # Check if this contained object should be ignored.
1012 if self._filter(val, name, valname):
1013 continue
1014 # Special handling for staticmethod/classmethod.
1015 if isinstance(val, staticmethod):
1016 val = getattr(obj, valname)
1017 if isinstance(val, classmethod):
1018 val = getattr(obj, valname).im_func
1019
1020 # Recurse to methods, properties, and nested classes.
1021 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001022 isinstance(val, property)) and
1023 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001024 valname = '%s.%s' % (name, valname)
1025 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001026 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001027
1028 def _get_test(self, obj, name, module, globs, source_lines):
1029 """
1030 Return a DocTest for the given object, if it defines a docstring;
1031 otherwise, return None.
1032 """
1033 # Extract the object's docstring. If it doesn't have one,
1034 # then return None (no test for this object).
1035 if isinstance(obj, basestring):
1036 docstring = obj
1037 else:
1038 try:
1039 if obj.__doc__ is None:
1040 return None
1041 docstring = str(obj.__doc__)
1042 except (TypeError, AttributeError):
1043 return None
1044
1045 # Don't bother if the docstring is empty.
1046 if not docstring:
1047 return None
1048
1049 # Find the docstring's location in the file.
1050 lineno = self._find_lineno(obj, source_lines)
1051
1052 # Return a DocTest for this object.
1053 if module is None:
1054 filename = None
1055 else:
1056 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001057 if filename[-4:] in (".pyc", ".pyo"):
1058 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001059 return self._parser.get_doctest(docstring, globs, name,
1060 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001061
1062 def _find_lineno(self, obj, source_lines):
1063 """
1064 Return a line number of the given object's docstring. Note:
1065 this method assumes that the object has a docstring.
1066 """
1067 lineno = None
1068
1069 # Find the line number for modules.
1070 if inspect.ismodule(obj):
1071 lineno = 0
1072
1073 # Find the line number for classes.
1074 # Note: this could be fooled if a class is defined multiple
1075 # times in a single file.
1076 if inspect.isclass(obj):
1077 if source_lines is None:
1078 return None
1079 pat = re.compile(r'^\s*class\s*%s\b' %
1080 getattr(obj, '__name__', '-'))
1081 for i, line in enumerate(source_lines):
1082 if pat.match(line):
1083 lineno = i
1084 break
1085
1086 # Find the line number for functions & methods.
1087 if inspect.ismethod(obj): obj = obj.im_func
1088 if inspect.isfunction(obj): obj = obj.func_code
1089 if inspect.istraceback(obj): obj = obj.tb_frame
1090 if inspect.isframe(obj): obj = obj.f_code
1091 if inspect.iscode(obj):
1092 lineno = getattr(obj, 'co_firstlineno', None)-1
1093
1094 # Find the line number where the docstring starts. Assume
1095 # that it's the first line that begins with a quote mark.
1096 # Note: this could be fooled by a multiline function
1097 # signature, where a continuation line begins with a quote
1098 # mark.
1099 if lineno is not None:
1100 if source_lines is None:
1101 return lineno+1
1102 pat = re.compile('(^|.*:)\s*\w*("|\')')
1103 for lineno in range(lineno, len(source_lines)):
1104 if pat.match(source_lines[lineno]):
1105 return lineno
1106
1107 # We couldn't find the line number.
1108 return None
1109
1110######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001111## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001112######################################################################
1113
Tim Peters8485b562004-08-04 18:46:34 +00001114class DocTestRunner:
1115 """
1116 A class used to run DocTest test cases, and accumulate statistics.
1117 The `run` method is used to process a single DocTest case. It
1118 returns a tuple `(f, t)`, where `t` is the number of test cases
1119 tried, and `f` is the number of test cases that failed.
1120
1121 >>> tests = DocTestFinder().find(_TestClass)
1122 >>> runner = DocTestRunner(verbose=False)
1123 >>> for test in tests:
1124 ... print runner.run(test)
1125 (0, 2)
1126 (0, 1)
1127 (0, 2)
1128 (0, 2)
1129
1130 The `summarize` method prints a summary of all the test cases that
1131 have been run by the runner, and returns an aggregated `(f, t)`
1132 tuple:
1133
1134 >>> runner.summarize(verbose=1)
1135 4 items passed all tests:
1136 2 tests in _TestClass
1137 2 tests in _TestClass.__init__
1138 2 tests in _TestClass.get
1139 1 tests in _TestClass.square
1140 7 tests in 4 items.
1141 7 passed and 0 failed.
1142 Test passed.
1143 (0, 7)
1144
1145 The aggregated number of tried examples and failed examples is
1146 also available via the `tries` and `failures` attributes:
1147
1148 >>> runner.tries
1149 7
1150 >>> runner.failures
1151 0
1152
1153 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001154 by an `OutputChecker`. This comparison may be customized with a
1155 number of option flags; see the documentation for `testmod` for
1156 more information. If the option flags are insufficient, then the
1157 comparison may also be customized by passing a subclass of
1158 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001159
1160 The test runner's display output can be controlled in two ways.
1161 First, an output function (`out) can be passed to
1162 `TestRunner.run`; this function will be called with strings that
1163 should be displayed. It defaults to `sys.stdout.write`. If
1164 capturing the output is not sufficient, then the display output
1165 can be also customized by subclassing DocTestRunner, and
1166 overriding the methods `report_start`, `report_success`,
1167 `report_unexpected_exception`, and `report_failure`.
1168 """
1169 # This divider string is used to separate failure messages, and to
1170 # separate sections of the summary.
1171 DIVIDER = "*" * 70
1172
Edward Loper34fcb142004-08-09 02:45:41 +00001173 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001174 """
1175 Create a new test runner.
1176
Edward Loper34fcb142004-08-09 02:45:41 +00001177 Optional keyword arg `checker` is the `OutputChecker` that
1178 should be used to compare the expected outputs and actual
1179 outputs of doctest examples.
1180
Tim Peters8485b562004-08-04 18:46:34 +00001181 Optional keyword arg 'verbose' prints lots of stuff if true,
1182 only failures if false; by default, it's true iff '-v' is in
1183 sys.argv.
1184
1185 Optional argument `optionflags` can be used to control how the
1186 test runner compares expected output to actual output, and how
1187 it displays failures. See the documentation for `testmod` for
1188 more information.
1189 """
Edward Loper34fcb142004-08-09 02:45:41 +00001190 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001191 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001192 verbose = '-v' in sys.argv
1193 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001194 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001195 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001196
Tim Peters8485b562004-08-04 18:46:34 +00001197 # Keep track of the examples we've run.
1198 self.tries = 0
1199 self.failures = 0
1200 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001201
Tim Peters8485b562004-08-04 18:46:34 +00001202 # Create a fake output target for capturing doctest output.
1203 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001204
Tim Peters8485b562004-08-04 18:46:34 +00001205 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001206 # Reporting methods
1207 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001208
Tim Peters8485b562004-08-04 18:46:34 +00001209 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001210 """
Tim Peters8485b562004-08-04 18:46:34 +00001211 Report that the test runner is about to process the given
1212 example. (Only displays a message if verbose=True)
1213 """
1214 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001215 if example.want:
1216 out('Trying:\n' + _indent(example.source) +
1217 'Expecting:\n' + _indent(example.want))
1218 else:
1219 out('Trying:\n' + _indent(example.source) +
1220 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001221
Tim Peters8485b562004-08-04 18:46:34 +00001222 def report_success(self, out, test, example, got):
1223 """
1224 Report that the given example ran successfully. (Only
1225 displays a message if verbose=True)
1226 """
1227 if self._verbose:
1228 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001229
Tim Peters8485b562004-08-04 18:46:34 +00001230 def report_failure(self, out, test, example, got):
1231 """
1232 Report that the given example failed.
1233 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001234 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001235 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001236
Tim Peters8485b562004-08-04 18:46:34 +00001237 def report_unexpected_exception(self, out, test, example, exc_info):
1238 """
1239 Report that the given example raised an unexpected exception.
1240 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001241 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001242 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001243
Edward Loper8e4a34b2004-08-12 02:34:27 +00001244 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001245 out = [self.DIVIDER]
1246 if test.filename:
1247 if test.lineno is not None and example.lineno is not None:
1248 lineno = test.lineno + example.lineno + 1
1249 else:
1250 lineno = '?'
1251 out.append('File "%s", line %s, in %s' %
1252 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001253 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001254 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1255 out.append('Failed example:')
1256 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001257 out.append(_indent(source))
1258 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001259
Tim Peters8485b562004-08-04 18:46:34 +00001260 #/////////////////////////////////////////////////////////////////
1261 # DocTest Running
1262 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001263
Tim Peters8485b562004-08-04 18:46:34 +00001264 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001265 """
Tim Peters8485b562004-08-04 18:46:34 +00001266 Run the examples in `test`. Write the outcome of each example
1267 with one of the `DocTestRunner.report_*` methods, using the
1268 writer function `out`. `compileflags` is the set of compiler
1269 flags that should be used to execute examples. Return a tuple
1270 `(f, t)`, where `t` is the number of examples tried, and `f`
1271 is the number of examples that failed. The examples are run
1272 in the namespace `test.globs`.
1273 """
1274 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001275 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001276
1277 # Save the option flags (since option directives can be used
1278 # to modify them).
1279 original_optionflags = self.optionflags
1280
1281 # Process each example.
Edward Loper2de91ba2004-08-27 02:07:46 +00001282 for examplenum, example in enumerate(test.examples):
1283
Edward Lopera89f88d2004-08-26 02:45:51 +00001284 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1285 # reporting after the first failure.
1286 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1287 failures > 0)
1288
Edward Loper74bca7a2004-08-12 02:27:44 +00001289 # Merge in the example's options.
1290 self.optionflags = original_optionflags
1291 if example.options:
1292 for (optionflag, val) in example.options.items():
1293 if val:
1294 self.optionflags |= optionflag
1295 else:
1296 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001297
1298 # Record that we started this example.
1299 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001300 if not quiet:
1301 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001302
Edward Loper2de91ba2004-08-27 02:07:46 +00001303 # Use a special filename for compile(), so we can retrieve
1304 # the source code during interactive debugging (see
1305 # __patched_linecache_getlines).
1306 filename = '<doctest %s[%d]>' % (test.name, examplenum)
1307
Tim Peters8485b562004-08-04 18:46:34 +00001308 # Run the example in the given context (globs), and record
1309 # any exception that gets raised. (But don't intercept
1310 # keyboard interrupts.)
1311 try:
Tim Peters208ca702004-08-09 04:12:36 +00001312 # Don't blink! This is where the user's code gets run.
Edward Loper2de91ba2004-08-27 02:07:46 +00001313 exec compile(example.source, filename, "single",
Tim Peters8485b562004-08-04 18:46:34 +00001314 compileflags, 1) in test.globs
Edward Loper2de91ba2004-08-27 02:07:46 +00001315 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001316 exception = None
1317 except KeyboardInterrupt:
1318 raise
1319 except:
1320 exception = sys.exc_info()
Edward Loper2de91ba2004-08-27 02:07:46 +00001321 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001322
Tim Peters208ca702004-08-09 04:12:36 +00001323 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001324 self._fakeout.truncate(0)
1325
1326 # If the example executed without raising any exceptions,
1327 # then verify its output and report its outcome.
1328 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001329 if self._checker.check_output(example.want, got,
1330 self.optionflags):
Edward Lopera89f88d2004-08-26 02:45:51 +00001331 if not quiet:
1332 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001333 else:
Edward Lopera89f88d2004-08-26 02:45:51 +00001334 if not quiet:
1335 self.report_failure(out, test, example, got)
Tim Peters8485b562004-08-04 18:46:34 +00001336 failures += 1
1337
1338 # If the example raised an exception, then check if it was
1339 # expected.
1340 else:
1341 exc_info = sys.exc_info()
1342 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1343
Edward Lopera6b68322004-08-26 00:05:43 +00001344 # If `example.exc_msg` is None, then we weren't
1345 # expecting an exception.
1346 if example.exc_msg is None:
Edward Lopera89f88d2004-08-26 02:45:51 +00001347 if not quiet:
1348 self.report_unexpected_exception(out, test, example,
1349 exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001350 failures += 1
Edward Lopera6b68322004-08-26 00:05:43 +00001351 # If `example.exc_msg` matches the actual exception
1352 # message (`exc_msg`), then the example succeeds.
1353 elif (self._checker.check_output(example.exc_msg, exc_msg,
1354 self.optionflags)):
Edward Lopera89f88d2004-08-26 02:45:51 +00001355 if not quiet:
1356 got += _exception_traceback(exc_info)
1357 self.report_success(out, test, example, got)
Edward Lopera6b68322004-08-26 00:05:43 +00001358 # Otherwise, the example fails.
Tim Peters8485b562004-08-04 18:46:34 +00001359 else:
Edward Lopera89f88d2004-08-26 02:45:51 +00001360 if not quiet:
1361 got += _exception_traceback(exc_info)
1362 self.report_failure(out, test, example, got)
Edward Lopera6b68322004-08-26 00:05:43 +00001363 failures += 1
Tim Peters8485b562004-08-04 18:46:34 +00001364
1365 # Restore the option flags (in case they were modified)
1366 self.optionflags = original_optionflags
1367
1368 # Record and return the number of failures and tries.
1369 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001370 return failures, tries
1371
Tim Peters8485b562004-08-04 18:46:34 +00001372 def __record_outcome(self, test, f, t):
1373 """
1374 Record the fact that the given DocTest (`test`) generated `f`
1375 failures out of `t` tried examples.
1376 """
1377 f2, t2 = self._name2ft.get(test.name, (0,0))
1378 self._name2ft[test.name] = (f+f2, t+t2)
1379 self.failures += f
1380 self.tries += t
1381
Edward Loper2de91ba2004-08-27 02:07:46 +00001382 __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1383 r'(?P<name>[\w\.]+)'
1384 r'\[(?P<examplenum>\d+)\]>$')
1385 def __patched_linecache_getlines(self, filename):
1386 m = self.__LINECACHE_FILENAME_RE.match(filename)
1387 if m and m.group('name') == self.test.name:
1388 example = self.test.examples[int(m.group('examplenum'))]
1389 return example.source.splitlines(True)
1390 else:
1391 return self.save_linecache_getlines(filename)
1392
Tim Peters8485b562004-08-04 18:46:34 +00001393 def run(self, test, compileflags=None, out=None, clear_globs=True):
1394 """
1395 Run the examples in `test`, and display the results using the
1396 writer function `out`.
1397
1398 The examples are run in the namespace `test.globs`. If
1399 `clear_globs` is true (the default), then this namespace will
1400 be cleared after the test runs, to help with garbage
1401 collection. If you would like to examine the namespace after
1402 the test completes, then use `clear_globs=False`.
1403
1404 `compileflags` gives the set of flags that should be used by
1405 the Python compiler when running the examples. If not
1406 specified, then it will default to the set of future-import
1407 flags that apply to `globs`.
1408
1409 The output of each example is checked using
1410 `DocTestRunner.check_output`, and the results are formatted by
1411 the `DocTestRunner.report_*` methods.
1412 """
Edward Loper2de91ba2004-08-27 02:07:46 +00001413 self.test = test
1414
Tim Peters8485b562004-08-04 18:46:34 +00001415 if compileflags is None:
1416 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001417
Tim Peters6c542b72004-08-09 16:43:36 +00001418 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001419 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001420 out = save_stdout.write
1421 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001422
Edward Loper2de91ba2004-08-27 02:07:46 +00001423 # Patch pdb.set_trace to restore sys.stdout during interactive
1424 # debugging (so it's not still redirected to self._fakeout).
1425 # Note that the interactive output will go to *our*
1426 # save_stdout, even if that's not the real sys.stdout; this
1427 # allows us to write test cases for the set_trace behavior.
Tim Peters6c542b72004-08-09 16:43:36 +00001428 save_set_trace = pdb.set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001429 self.debugger = _OutputRedirectingPdb(save_stdout)
1430 self.debugger.reset()
1431 pdb.set_trace = self.debugger.set_trace
1432
1433 # Patch linecache.getlines, so we can see the example's source
1434 # when we're inside the debugger.
1435 self.save_linecache_getlines = linecache.getlines
1436 linecache.getlines = self.__patched_linecache_getlines
1437
Tim Peters8485b562004-08-04 18:46:34 +00001438 try:
Tim Peters8485b562004-08-04 18:46:34 +00001439 return self.__run(test, compileflags, out)
1440 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001441 sys.stdout = save_stdout
1442 pdb.set_trace = save_set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001443 linecache.getlines = self.save_linecache_getlines
Tim Peters8485b562004-08-04 18:46:34 +00001444 if clear_globs:
1445 test.globs.clear()
1446
1447 #/////////////////////////////////////////////////////////////////
1448 # Summarization
1449 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001450 def summarize(self, verbose=None):
1451 """
Tim Peters8485b562004-08-04 18:46:34 +00001452 Print a summary of all the test cases that have been run by
1453 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1454 the total number of failed examples, and `t` is the total
1455 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001456
Tim Peters8485b562004-08-04 18:46:34 +00001457 The optional `verbose` argument controls how detailed the
1458 summary is. If the verbosity is not specified, then the
1459 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001460 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001461 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001462 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001463 notests = []
1464 passed = []
1465 failed = []
1466 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001467 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001468 name, (f, t) = x
1469 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001470 totalt += t
1471 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001472 if t == 0:
1473 notests.append(name)
1474 elif f == 0:
1475 passed.append( (name, t) )
1476 else:
1477 failed.append(x)
1478 if verbose:
1479 if notests:
1480 print len(notests), "items had no tests:"
1481 notests.sort()
1482 for thing in notests:
1483 print " ", thing
1484 if passed:
1485 print len(passed), "items passed all tests:"
1486 passed.sort()
1487 for thing, count in passed:
1488 print " %3d tests in %s" % (count, thing)
1489 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001490 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001491 print len(failed), "items had failures:"
1492 failed.sort()
1493 for thing, (f, t) in failed:
1494 print " %3d of %3d in %s" % (f, t, thing)
1495 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001496 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001497 print totalt - totalf, "passed and", totalf, "failed."
1498 if totalf:
1499 print "***Test Failed***", totalf, "failures."
1500 elif verbose:
1501 print "Test passed."
1502 return totalf, totalt
1503
Edward Loper34fcb142004-08-09 02:45:41 +00001504class OutputChecker:
1505 """
1506 A class used to check the whether the actual output from a doctest
1507 example matches the expected output. `OutputChecker` defines two
1508 methods: `check_output`, which compares a given pair of outputs,
1509 and returns true if they match; and `output_difference`, which
1510 returns a string describing the differences between two outputs.
1511 """
1512 def check_output(self, want, got, optionflags):
1513 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001514 Return True iff the actual output from an example (`got`)
1515 matches the expected output (`want`). These strings are
1516 always considered to match if they are identical; but
1517 depending on what option flags the test runner is using,
1518 several non-exact match types are also possible. See the
1519 documentation for `TestRunner` for more information about
1520 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001521 """
1522 # Handle the common case first, for efficiency:
1523 # if they're string-identical, always return true.
1524 if got == want:
1525 return True
1526
1527 # The values True and False replaced 1 and 0 as the return
1528 # value for boolean comparisons in Python 2.3.
1529 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1530 if (got,want) == ("True\n", "1\n"):
1531 return True
1532 if (got,want) == ("False\n", "0\n"):
1533 return True
1534
1535 # <BLANKLINE> can be used as a special sequence to signify a
1536 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1537 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1538 # Replace <BLANKLINE> in want with a blank line.
1539 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1540 '', want)
1541 # If a line in got contains only spaces, then remove the
1542 # spaces.
1543 got = re.sub('(?m)^\s*?$', '', got)
1544 if got == want:
1545 return True
1546
1547 # This flag causes doctest to ignore any differences in the
1548 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001549 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001550 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001551 got = ' '.join(got.split())
1552 want = ' '.join(want.split())
1553 if got == want:
1554 return True
1555
1556 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001557 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001558 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001559 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001560 return True
1561
1562 # We didn't find any match; return false.
1563 return False
1564
Tim Petersc6cbab02004-08-22 19:43:28 +00001565 # Should we do a fancy diff?
1566 def _do_a_fancy_diff(self, want, got, optionflags):
1567 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001568 if not optionflags & (REPORT_UDIFF |
1569 REPORT_CDIFF |
1570 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001571 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001572
Tim Petersc6cbab02004-08-22 19:43:28 +00001573 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001574 # too hard ... or maybe not. In two real-life failures Tim saw,
1575 # a diff was a major help anyway, so this is commented out.
1576 # [todo] _ellipsis_match() knows which pieces do and don't match,
1577 # and could be the basis for a kick-ass diff in this case.
1578 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1579 ## return False
1580
Tim Petersc6cbab02004-08-22 19:43:28 +00001581 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001582 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001583 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001584 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001585
Tim Petersc6cbab02004-08-22 19:43:28 +00001586 # The other diff types need at least a few lines to be helpful.
1587 return want.count('\n') > 2 and got.count('\n') > 2
1588
Edward Loperca9111e2004-08-26 03:00:24 +00001589 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001590 """
1591 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001592 expected output for a given example (`example`) and the actual
1593 output (`got`). `optionflags` is the set of option flags used
1594 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001595 """
Edward Loperca9111e2004-08-26 03:00:24 +00001596 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001597 # If <BLANKLINE>s are being used, then replace blank lines
1598 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001599 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001600 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001601
Tim Peters5b799c12004-08-26 05:21:59 +00001602 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001603 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001604 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001605 want_lines = want.splitlines(True) # True == keep line ends
1606 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001607 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001608 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001609 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1610 diff = list(diff)[2:] # strip the diff header
1611 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001612 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001613 diff = difflib.context_diff(want_lines, got_lines, n=2)
1614 diff = list(diff)[2:] # strip the diff header
1615 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001616 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001617 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1618 diff = list(engine.compare(want_lines, got_lines))
1619 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001620 else:
1621 assert 0, 'Bad diff option'
1622 # Remove trailing whitespace on diff output.
1623 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001624 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001625
1626 # If we're not using diff, then simply list the expected
1627 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001628 if want and got:
1629 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1630 elif want:
1631 return 'Expected:\n%sGot nothing\n' % _indent(want)
1632 elif got:
1633 return 'Expected nothing\nGot:\n%s' % _indent(got)
1634 else:
1635 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001636
Tim Peters19397e52004-08-06 22:02:59 +00001637class DocTestFailure(Exception):
1638 """A DocTest example has failed in debugging mode.
1639
1640 The exception instance has variables:
1641
1642 - test: the DocTest object being run
1643
1644 - excample: the Example object that failed
1645
1646 - got: the actual output
1647 """
1648 def __init__(self, test, example, got):
1649 self.test = test
1650 self.example = example
1651 self.got = got
1652
1653 def __str__(self):
1654 return str(self.test)
1655
1656class UnexpectedException(Exception):
1657 """A DocTest example has encountered an unexpected exception
1658
1659 The exception instance has variables:
1660
1661 - test: the DocTest object being run
1662
1663 - excample: the Example object that failed
1664
1665 - exc_info: the exception info
1666 """
1667 def __init__(self, test, example, exc_info):
1668 self.test = test
1669 self.example = example
1670 self.exc_info = exc_info
1671
1672 def __str__(self):
1673 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001674
Tim Peters19397e52004-08-06 22:02:59 +00001675class DebugRunner(DocTestRunner):
1676 r"""Run doc tests but raise an exception as soon as there is a failure.
1677
1678 If an unexpected exception occurs, an UnexpectedException is raised.
1679 It contains the test, the example, and the original exception:
1680
1681 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001682 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1683 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001684 >>> try:
1685 ... runner.run(test)
1686 ... except UnexpectedException, failure:
1687 ... pass
1688
1689 >>> failure.test is test
1690 True
1691
1692 >>> failure.example.want
1693 '42\n'
1694
1695 >>> exc_info = failure.exc_info
1696 >>> raise exc_info[0], exc_info[1], exc_info[2]
1697 Traceback (most recent call last):
1698 ...
1699 KeyError
1700
1701 We wrap the original exception to give the calling application
1702 access to the test and example information.
1703
1704 If the output doesn't match, then a DocTestFailure is raised:
1705
Edward Lopera1ef6112004-08-09 16:14:41 +00001706 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001707 ... >>> x = 1
1708 ... >>> x
1709 ... 2
1710 ... ''', {}, 'foo', 'foo.py', 0)
1711
1712 >>> try:
1713 ... runner.run(test)
1714 ... except DocTestFailure, failure:
1715 ... pass
1716
1717 DocTestFailure objects provide access to the test:
1718
1719 >>> failure.test is test
1720 True
1721
1722 As well as to the example:
1723
1724 >>> failure.example.want
1725 '2\n'
1726
1727 and the actual output:
1728
1729 >>> failure.got
1730 '1\n'
1731
1732 If a failure or error occurs, the globals are left intact:
1733
1734 >>> del test.globs['__builtins__']
1735 >>> test.globs
1736 {'x': 1}
1737
Edward Lopera1ef6112004-08-09 16:14:41 +00001738 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001739 ... >>> x = 2
1740 ... >>> raise KeyError
1741 ... ''', {}, 'foo', 'foo.py', 0)
1742
1743 >>> runner.run(test)
1744 Traceback (most recent call last):
1745 ...
1746 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001747
Tim Peters19397e52004-08-06 22:02:59 +00001748 >>> del test.globs['__builtins__']
1749 >>> test.globs
1750 {'x': 2}
1751
1752 But the globals are cleared if there is no error:
1753
Edward Lopera1ef6112004-08-09 16:14:41 +00001754 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001755 ... >>> x = 2
1756 ... ''', {}, 'foo', 'foo.py', 0)
1757
1758 >>> runner.run(test)
1759 (0, 1)
1760
1761 >>> test.globs
1762 {}
1763
1764 """
1765
1766 def run(self, test, compileflags=None, out=None, clear_globs=True):
1767 r = DocTestRunner.run(self, test, compileflags, out, False)
1768 if clear_globs:
1769 test.globs.clear()
1770 return r
1771
1772 def report_unexpected_exception(self, out, test, example, exc_info):
1773 raise UnexpectedException(test, example, exc_info)
1774
1775 def report_failure(self, out, test, example, got):
1776 raise DocTestFailure(test, example, got)
1777
Tim Peters8485b562004-08-04 18:46:34 +00001778######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001779## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001780######################################################################
1781# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001782
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001783def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001784 report=True, optionflags=0, extraglobs=None,
1785 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001786 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001787 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001788
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001789 Test examples in docstrings in functions and classes reachable
1790 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001791 with m.__doc__. Unless isprivate is specified, private names
1792 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001793
1794 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001795 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001796 function and class docstrings are tested even if the name is private;
1797 strings are tested directly, as if they were docstrings.
1798
1799 Return (#failures, #tests).
1800
1801 See doctest.__doc__ for an overview.
1802
1803 Optional keyword arg "name" gives the name of the module; by default
1804 use m.__name__.
1805
1806 Optional keyword arg "globs" gives a dict to be used as the globals
1807 when executing examples; by default, use m.__dict__. A copy of this
1808 dict is actually used for each docstring, so that each docstring's
1809 examples start with a clean slate.
1810
Tim Peters8485b562004-08-04 18:46:34 +00001811 Optional keyword arg "extraglobs" gives a dictionary that should be
1812 merged into the globals that are used to execute examples. By
1813 default, no extra globals are used. This is new in 2.4.
1814
Tim Peters8a7d2d52001-01-16 07:10:57 +00001815 Optional keyword arg "verbose" prints lots of stuff if true, prints
1816 only failures if false; by default, it's true iff "-v" is in sys.argv.
1817
Tim Peters8a7d2d52001-01-16 07:10:57 +00001818 Optional keyword arg "report" prints a summary at the end when true,
1819 else prints nothing at the end. In verbose mode, the summary is
1820 detailed, else very brief (in fact, empty if all tests passed).
1821
Tim Peters6ebe61f2003-06-27 20:48:05 +00001822 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001823 and defaults to 0. This is new in 2.3. Possible values (see the
1824 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001825
1826 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001827 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001828 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001829 ELLIPSIS
Edward Loper71f55af2004-08-26 01:41:51 +00001830 REPORT_UDIFF
1831 REPORT_CDIFF
1832 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001833 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001834
1835 Optional keyword arg "raise_on_error" raises an exception on the
1836 first unexpected exception or failure. This allows failures to be
1837 post-mortem debugged.
1838
Tim Petersf727c6c2004-08-08 01:48:59 +00001839 Deprecated in Python 2.4:
1840 Optional keyword arg "isprivate" specifies a function used to
1841 determine whether a name is private. The default function is
1842 treat all functions as public. Optionally, "isprivate" can be
1843 set to doctest.is_private to skip over functions marked as private
1844 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001845 """
1846
1847 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001848 Advanced tomfoolery: testmod runs methods of a local instance of
1849 class doctest.Tester, then merges the results into (or creates)
1850 global Tester instance doctest.master. Methods of doctest.master
1851 can be called directly too, if you want to do something unusual.
1852 Passing report=0 to testmod is especially useful then, to delay
1853 displaying a summary. Invoke doctest.master.summarize(verbose)
1854 when you're done fiddling.
1855 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001856 if isprivate is not None:
1857 warnings.warn("the isprivate argument is deprecated; "
1858 "examine DocTestFinder.find() lists instead",
1859 DeprecationWarning)
1860
Tim Peters8485b562004-08-04 18:46:34 +00001861 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001862 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001863 # DWA - m will still be None if this wasn't invoked from the command
1864 # line, in which case the following TypeError is about as good an error
1865 # as we should expect
1866 m = sys.modules.get('__main__')
1867
Tim Peters8485b562004-08-04 18:46:34 +00001868 # Check that we were actually given a module.
1869 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001870 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001871
1872 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001873 if name is None:
1874 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001875
1876 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001877 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001878
1879 if raise_on_error:
1880 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1881 else:
1882 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1883
Tim Peters8485b562004-08-04 18:46:34 +00001884 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1885 runner.run(test)
1886
Tim Peters8a7d2d52001-01-16 07:10:57 +00001887 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001888 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001889
Tim Peters8485b562004-08-04 18:46:34 +00001890 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001891
Tim Peters8485b562004-08-04 18:46:34 +00001892def run_docstring_examples(f, globs, verbose=False, name="NoName",
1893 compileflags=None, optionflags=0):
1894 """
1895 Test examples in the given object's docstring (`f`), using `globs`
1896 as globals. Optional argument `name` is used in failure messages.
1897 If the optional argument `verbose` is true, then generate output
1898 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001899
Tim Peters8485b562004-08-04 18:46:34 +00001900 `compileflags` gives the set of flags that should be used by the
1901 Python compiler when running the examples. If not specified, then
1902 it will default to the set of future-import flags that apply to
1903 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001904
Tim Peters8485b562004-08-04 18:46:34 +00001905 Optional keyword arg `optionflags` specifies options for the
1906 testing and output. See the documentation for `testmod` for more
1907 information.
1908 """
1909 # Find, parse, and run all tests in the given module.
1910 finder = DocTestFinder(verbose=verbose, recurse=False)
1911 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1912 for test in finder.find(f, name, globs=globs):
1913 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001914
Tim Peters8485b562004-08-04 18:46:34 +00001915######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001916## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001917######################################################################
1918# This is provided only for backwards compatibility. It's not
1919# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001920
Tim Peters8485b562004-08-04 18:46:34 +00001921class Tester:
1922 def __init__(self, mod=None, globs=None, verbose=None,
1923 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001924
1925 warnings.warn("class Tester is deprecated; "
1926 "use class doctest.DocTestRunner instead",
1927 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001928 if mod is None and globs is None:
1929 raise TypeError("Tester.__init__: must specify mod or globs")
1930 if mod is not None and not _ismodule(mod):
1931 raise TypeError("Tester.__init__: mod must be a module; %r" %
1932 (mod,))
1933 if globs is None:
1934 globs = mod.__dict__
1935 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001936
Tim Peters8485b562004-08-04 18:46:34 +00001937 self.verbose = verbose
1938 self.isprivate = isprivate
1939 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001940 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001941 self.testrunner = DocTestRunner(verbose=verbose,
1942 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001943
Tim Peters8485b562004-08-04 18:46:34 +00001944 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001945 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001946 if self.verbose:
1947 print "Running string", name
1948 (f,t) = self.testrunner.run(test)
1949 if self.verbose:
1950 print f, "of", t, "examples failed in string", name
1951 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001952
Tim Petersf3f57472004-08-08 06:11:48 +00001953 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001954 f = t = 0
1955 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001956 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001957 for test in tests:
1958 (f2, t2) = self.testrunner.run(test)
1959 (f,t) = (f+f2, t+t2)
1960 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001961
Tim Peters8485b562004-08-04 18:46:34 +00001962 def rundict(self, d, name, module=None):
1963 import new
1964 m = new.module(name)
1965 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001966 if module is None:
1967 module = False
1968 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001969
Tim Peters8485b562004-08-04 18:46:34 +00001970 def run__test__(self, d, name):
1971 import new
1972 m = new.module(name)
1973 m.__test__ = d
1974 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001975
Tim Peters8485b562004-08-04 18:46:34 +00001976 def summarize(self, verbose=None):
1977 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001978
Tim Peters8485b562004-08-04 18:46:34 +00001979 def merge(self, other):
1980 d = self.testrunner._name2ft
1981 for name, (f, t) in other.testrunner._name2ft.items():
1982 if name in d:
1983 print "*** Tester.merge: '" + name + "' in both" \
1984 " testers; summing outcomes."
1985 f2, t2 = d[name]
1986 f = f + f2
1987 t = t + t2
1988 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001989
Tim Peters8485b562004-08-04 18:46:34 +00001990######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001991## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001992######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001993
Tim Peters19397e52004-08-06 22:02:59 +00001994class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001995
Edward Loper34fcb142004-08-09 02:45:41 +00001996 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
1997 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00001998
Jim Fultona643b652004-07-14 19:06:50 +00001999 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002000 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002001 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002002 self._dt_test = test
2003 self._dt_setUp = setUp
2004 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002005
Jim Fultona643b652004-07-14 19:06:50 +00002006 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00002007 if self._dt_setUp is not None:
2008 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00002009
2010 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00002011 if self._dt_tearDown is not None:
2012 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002013
2014 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002015 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002016 old = sys.stdout
2017 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00002018 runner = DocTestRunner(optionflags=self._dt_optionflags,
2019 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002020
Jim Fultona643b652004-07-14 19:06:50 +00002021 try:
Tim Peters19397e52004-08-06 22:02:59 +00002022 runner.DIVIDER = "-"*70
2023 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00002024 finally:
2025 sys.stdout = old
2026
2027 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002028 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002029
Tim Peters19397e52004-08-06 22:02:59 +00002030 def format_failure(self, err):
2031 test = self._dt_test
2032 if test.lineno is None:
2033 lineno = 'unknown line number'
2034 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002035 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002036 lname = '.'.join(test.name.split('.')[-1:])
2037 return ('Failed doctest test for %s\n'
2038 ' File "%s", line %s, in %s\n\n%s'
2039 % (test.name, test.filename, lineno, lname, err)
2040 )
2041
2042 def debug(self):
2043 r"""Run the test case without results and without catching exceptions
2044
2045 The unit test framework includes a debug method on test cases
2046 and test suites to support post-mortem debugging. The test code
2047 is run in such a way that errors are not caught. This way a
2048 caller can catch the errors and initiate post-mortem debugging.
2049
2050 The DocTestCase provides a debug method that raises
2051 UnexpectedException errors if there is an unexepcted
2052 exception:
2053
Edward Lopera1ef6112004-08-09 16:14:41 +00002054 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002055 ... {}, 'foo', 'foo.py', 0)
2056 >>> case = DocTestCase(test)
2057 >>> try:
2058 ... case.debug()
2059 ... except UnexpectedException, failure:
2060 ... pass
2061
2062 The UnexpectedException contains the test, the example, and
2063 the original exception:
2064
2065 >>> failure.test is test
2066 True
2067
2068 >>> failure.example.want
2069 '42\n'
2070
2071 >>> exc_info = failure.exc_info
2072 >>> raise exc_info[0], exc_info[1], exc_info[2]
2073 Traceback (most recent call last):
2074 ...
2075 KeyError
2076
2077 If the output doesn't match, then a DocTestFailure is raised:
2078
Edward Lopera1ef6112004-08-09 16:14:41 +00002079 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002080 ... >>> x = 1
2081 ... >>> x
2082 ... 2
2083 ... ''', {}, 'foo', 'foo.py', 0)
2084 >>> case = DocTestCase(test)
2085
2086 >>> try:
2087 ... case.debug()
2088 ... except DocTestFailure, failure:
2089 ... pass
2090
2091 DocTestFailure objects provide access to the test:
2092
2093 >>> failure.test is test
2094 True
2095
2096 As well as to the example:
2097
2098 >>> failure.example.want
2099 '2\n'
2100
2101 and the actual output:
2102
2103 >>> failure.got
2104 '1\n'
2105
2106 """
2107
Edward Loper34fcb142004-08-09 02:45:41 +00002108 runner = DebugRunner(optionflags=self._dt_optionflags,
2109 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002110 runner.run(self._dt_test)
Jim Fultona643b652004-07-14 19:06:50 +00002111
2112 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002113 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002114
2115 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002116 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002117 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2118
2119 __str__ = __repr__
2120
2121 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002122 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002123
Tim Peters19397e52004-08-06 22:02:59 +00002124def DocTestSuite(module=None, globs=None, extraglobs=None,
2125 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002126 setUp=lambda: None, tearDown=lambda: None,
2127 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002128 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002129 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002130
Tim Peters19397e52004-08-06 22:02:59 +00002131 This converts each documentation string in a module that
2132 contains doctest tests to a unittest test case. If any of the
2133 tests in a doc string fail, then the test case fails. An exception
2134 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002135 (sometimes approximate) line number.
2136
Tim Peters19397e52004-08-06 22:02:59 +00002137 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002138 can be either a module or a module name.
2139
2140 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002141 """
Jim Fultona643b652004-07-14 19:06:50 +00002142
Tim Peters8485b562004-08-04 18:46:34 +00002143 if test_finder is None:
2144 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002145
Tim Peters19397e52004-08-06 22:02:59 +00002146 module = _normalize_module(module)
2147 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2148 if globs is None:
2149 globs = module.__dict__
2150 if not tests: # [XX] why do we want to do this?
2151 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002152
2153 tests.sort()
2154 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002155 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002156 if len(test.examples) == 0:
2157 continue
Tim Peters8485b562004-08-04 18:46:34 +00002158 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002159 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002160 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002161 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002162 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002163 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2164 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002165
2166 return suite
2167
2168class DocFileCase(DocTestCase):
2169
2170 def id(self):
2171 return '_'.join(self._dt_test.name.split('.'))
2172
2173 def __repr__(self):
2174 return self._dt_test.filename
2175 __str__ = __repr__
2176
2177 def format_failure(self, err):
2178 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2179 % (self._dt_test.name, self._dt_test.filename, err)
2180 )
2181
2182def DocFileTest(path, package=None, globs=None,
2183 setUp=None, tearDown=None,
2184 optionflags=0):
2185 package = _normalize_module(package)
2186 name = path.split('/')[-1]
2187 dir = os.path.split(package.__file__)[0]
2188 path = os.path.join(dir, *(path.split('/')))
2189 doc = open(path).read()
2190
2191 if globs is None:
2192 globs = {}
2193
Edward Lopera1ef6112004-08-09 16:14:41 +00002194 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002195
2196 return DocFileCase(test, optionflags, setUp, tearDown)
2197
2198def DocFileSuite(*paths, **kw):
2199 """Creates a suite of doctest files.
2200
2201 One or more text file paths are given as strings. These should
2202 use "/" characters to separate path segments. Paths are relative
2203 to the directory of the calling module, or relative to the package
2204 passed as a keyword argument.
2205
2206 A number of options may be provided as keyword arguments:
2207
2208 package
2209 The name of a Python package. Text-file paths will be
2210 interpreted relative to the directory containing this package.
2211 The package may be supplied as a package object or as a dotted
2212 package name.
2213
2214 setUp
2215 The name of a set-up function. This is called before running the
2216 tests in each file.
2217
2218 tearDown
2219 The name of a tear-down function. This is called after running the
2220 tests in each file.
2221
2222 globs
2223 A dictionary containing initial global variables for the tests.
2224 """
2225 suite = unittest.TestSuite()
2226
2227 # We do this here so that _normalize_module is called at the right
2228 # level. If it were called in DocFileTest, then this function
2229 # would be the caller and we might guess the package incorrectly.
2230 kw['package'] = _normalize_module(kw.get('package'))
2231
2232 for path in paths:
2233 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002234
Tim Petersdb3756d2003-06-29 05:30:48 +00002235 return suite
2236
Tim Peters8485b562004-08-04 18:46:34 +00002237######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002238## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002239######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002240
Tim Peters19397e52004-08-06 22:02:59 +00002241def script_from_examples(s):
2242 r"""Extract script from text with examples.
2243
2244 Converts text with examples to a Python script. Example input is
2245 converted to regular code. Example output and all other words
2246 are converted to comments:
2247
2248 >>> text = '''
2249 ... Here are examples of simple math.
2250 ...
2251 ... Python has super accurate integer addition
2252 ...
2253 ... >>> 2 + 2
2254 ... 5
2255 ...
2256 ... And very friendly error messages:
2257 ...
2258 ... >>> 1/0
2259 ... To Infinity
2260 ... And
2261 ... Beyond
2262 ...
2263 ... You can use logic if you want:
2264 ...
2265 ... >>> if 0:
2266 ... ... blah
2267 ... ... blah
2268 ... ...
2269 ...
2270 ... Ho hum
2271 ... '''
2272
2273 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002274 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002275 #
Edward Lopera5db6002004-08-12 02:41:30 +00002276 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002277 #
2278 2 + 2
2279 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002280 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002281 #
Edward Lopera5db6002004-08-12 02:41:30 +00002282 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002283 #
2284 1/0
2285 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002286 ## To Infinity
2287 ## And
2288 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002289 #
Edward Lopera5db6002004-08-12 02:41:30 +00002290 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002291 #
2292 if 0:
2293 blah
2294 blah
Tim Peters19397e52004-08-06 22:02:59 +00002295 #
Edward Lopera5db6002004-08-12 02:41:30 +00002296 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002297 """
Edward Loper00f8da72004-08-26 18:05:07 +00002298 output = []
2299 for piece in DocTestParser().parse(s):
2300 if isinstance(piece, Example):
2301 # Add the example's source code (strip trailing NL)
2302 output.append(piece.source[:-1])
2303 # Add the expected output:
2304 want = piece.want
2305 if want:
2306 output.append('# Expected:')
2307 output += ['## '+l for l in want.split('\n')[:-1]]
2308 else:
2309 # Add non-example text.
2310 output += [_comment_line(l)
2311 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002312
Edward Loper00f8da72004-08-26 18:05:07 +00002313 # Trim junk on both ends.
2314 while output and output[-1] == '#':
2315 output.pop()
2316 while output and output[0] == '#':
2317 output.pop(0)
2318 # Combine the output, and return it.
2319 return '\n'.join(output)
Tim Petersdb3756d2003-06-29 05:30:48 +00002320
2321def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002322 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002323
2324 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002325 test to be debugged and the name (within the module) of the object
2326 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002327 """
Tim Peters8485b562004-08-04 18:46:34 +00002328 module = _normalize_module(module)
2329 tests = DocTestFinder().find(module)
2330 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002331 if not test:
2332 raise ValueError(name, "not found in tests")
2333 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002334 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002335 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002336
Jim Fultona643b652004-07-14 19:06:50 +00002337def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002338 """Debug a single doctest docstring, in argument `src`'"""
2339 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002340 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002341
Jim Fultona643b652004-07-14 19:06:50 +00002342def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002343 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002344 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002345
Tim Petersb6a04d62004-08-23 21:37:56 +00002346 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2347 # docs say, a file so created cannot be opened by name a second time
2348 # on modern Windows boxes, and execfile() needs to open it.
2349 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002350 f = open(srcfilename, 'w')
2351 f.write(src)
2352 f.close()
2353
Tim Petersb6a04d62004-08-23 21:37:56 +00002354 try:
2355 if globs:
2356 globs = globs.copy()
2357 else:
2358 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002359
Tim Petersb6a04d62004-08-23 21:37:56 +00002360 if pm:
2361 try:
2362 execfile(srcfilename, globs, globs)
2363 except:
2364 print sys.exc_info()[1]
2365 pdb.post_mortem(sys.exc_info()[2])
2366 else:
2367 # Note that %r is vital here. '%s' instead can, e.g., cause
2368 # backslashes to get treated as metacharacters on Windows.
2369 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2370
2371 finally:
2372 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002373
Jim Fultona643b652004-07-14 19:06:50 +00002374def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002375 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002376
2377 Provide the module (or dotted name of the module) containing the
2378 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002379 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002380 """
Tim Peters8485b562004-08-04 18:46:34 +00002381 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002382 testsrc = testsource(module, name)
2383 debug_script(testsrc, pm, module.__dict__)
2384
Tim Peters8485b562004-08-04 18:46:34 +00002385######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002386## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002387######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002388class _TestClass:
2389 """
2390 A pointless class, for sanity-checking of docstring testing.
2391
2392 Methods:
2393 square()
2394 get()
2395
2396 >>> _TestClass(13).get() + _TestClass(-12).get()
2397 1
2398 >>> hex(_TestClass(13).square().get())
2399 '0xa9'
2400 """
2401
2402 def __init__(self, val):
2403 """val -> _TestClass object with associated value val.
2404
2405 >>> t = _TestClass(123)
2406 >>> print t.get()
2407 123
2408 """
2409
2410 self.val = val
2411
2412 def square(self):
2413 """square() -> square TestClass's associated value
2414
2415 >>> _TestClass(13).square().get()
2416 169
2417 """
2418
2419 self.val = self.val ** 2
2420 return self
2421
2422 def get(self):
2423 """get() -> return TestClass's associated value.
2424
2425 >>> x = _TestClass(-42)
2426 >>> print x.get()
2427 -42
2428 """
2429
2430 return self.val
2431
2432__test__ = {"_TestClass": _TestClass,
2433 "string": r"""
2434 Example of a string object, searched as-is.
2435 >>> x = 1; y = 2
2436 >>> x + y, x * y
2437 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002438 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002439
Tim Peters6ebe61f2003-06-27 20:48:05 +00002440 "bool-int equivalence": r"""
2441 In 2.2, boolean expressions displayed
2442 0 or 1. By default, we still accept
2443 them. This can be disabled by passing
2444 DONT_ACCEPT_TRUE_FOR_1 to the new
2445 optionflags argument.
2446 >>> 4 == 4
2447 1
2448 >>> 4 == 4
2449 True
2450 >>> 4 > 4
2451 0
2452 >>> 4 > 4
2453 False
2454 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002455
Tim Peters8485b562004-08-04 18:46:34 +00002456 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002457 Blank lines can be marked with <BLANKLINE>:
2458 >>> print 'foo\n\nbar\n'
2459 foo
2460 <BLANKLINE>
2461 bar
2462 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002463 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002464
2465 "ellipsis": r"""
2466 If the ellipsis flag is used, then '...' can be used to
2467 elide substrings in the desired output:
2468 >>> print range(1000) #doctest: +ELLIPSIS
2469 [0, 1, 2, ..., 999]
2470 """,
2471
2472 "whitespace normalization": r"""
2473 If the whitespace normalization flag is used, then
2474 differences in whitespace are ignored.
2475 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2476 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2477 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2478 27, 28, 29]
2479 """,
2480 }
Tim Peters8485b562004-08-04 18:46:34 +00002481
Tim Peters8a7d2d52001-01-16 07:10:57 +00002482def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002483 r = unittest.TextTestRunner()
2484 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002485
2486if __name__ == "__main__":
2487 _test()