blob: bcdc567bdcafbc6d17ef216851c3b7485910a37c [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8485b562004-08-04 18:46:34 +00002# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
Tim Peters19397e52004-08-06 22:02:59 +00003# Major enhancements and refactoring by:
Tim Peters8485b562004-08-04 18:46:34 +00004# Jim Fulton
5# Edward Loper
Tim Peters8a7d2d52001-01-16 07:10:57 +00006
7# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
8
Martin v. Löwis92816de2004-05-31 19:01:00 +00009r"""Module doctest -- a framework for running examples in docstrings.
Tim Peters8a7d2d52001-01-16 07:10:57 +000010
11NORMAL USAGE
12
Tim Peters80e53142004-08-09 04:34:45 +000013In simplest use, end each module M to be tested with:
Tim Peters8a7d2d52001-01-16 07:10:57 +000014
15def _test():
Tim Peters80e53142004-08-09 04:34:45 +000016 import doctest
17 return doctest.testmod()
Tim Peters8a7d2d52001-01-16 07:10:57 +000018
19if __name__ == "__main__":
20 _test()
21
22Then running the module as a script will cause the examples in the
23docstrings to get executed and verified:
24
25python M.py
26
27This won't display anything unless an example fails, in which case the
28failing example(s) and the cause(s) of the failure(s) are printed to stdout
29(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
30line of output is "Test failed.".
31
32Run it with the -v switch instead:
33
34python M.py -v
35
36and a detailed report of all examples tried is printed to stdout, along
37with assorted summaries at the end.
38
Tim Peters80e53142004-08-09 04:34:45 +000039You can force verbose mode by passing "verbose=True" to testmod, or prohibit
40it by passing "verbose=False". In either of those cases, sys.argv is not
Tim Peters8a7d2d52001-01-16 07:10:57 +000041examined by testmod.
42
43In any case, testmod returns a 2-tuple of ints (f, t), where f is the
44number of docstring examples that failed and t is the total number of
45docstring examples attempted.
46
Tim Peters80e53142004-08-09 04:34:45 +000047There are a variety of other ways to run doctests, including integration
48with the unittest framework, and support for running non-Python text
49files containing doctests. There are also many ways to override parts
50of doctest's default behaviors. See the Library Reference Manual for
51details.
52
Tim Peters8a7d2d52001-01-16 07:10:57 +000053
54WHICH DOCSTRINGS ARE EXAMINED?
55
56+ M.__doc__.
57
58+ f.__doc__ for all functions f in M.__dict__.values(), except those
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000059 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000060
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000061+ C.__doc__ for all classes C in M.__dict__.values(), except those
62 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000063
64+ If M.__test__ exists and "is true", it must be a dict, and
65 each entry maps a (string) name to a function object, class object, or
66 string. Function and class object docstrings found from M.__test__
Tim Peters80e53142004-08-09 04:34:45 +000067 are searched, and strings are searched directly as if they were docstrings.
68 In output, a key K in M.__test__ appears with name
Tim Peters8a7d2d52001-01-16 07:10:57 +000069 <name of M>.__test__.K
70
71Any classes found are recursively searched similarly, to test docstrings in
Tim Peters80e53142004-08-09 04:34:45 +000072their contained methods and nested classes.
Tim Peters8a7d2d52001-01-16 07:10:57 +000073
Tim Peters8a7d2d52001-01-16 07:10:57 +000074
Tim Peters8a7d2d52001-01-16 07:10:57 +000075WHAT'S THE EXECUTION CONTEXT?
76
77By default, each time testmod finds a docstring to test, it uses a *copy*
78of M's globals (so that running tests on a module doesn't change the
79module's real globals, and so that one test in M can't leave behind crumbs
80that accidentally allow another test to work). This means examples can
81freely use any names defined at top-level in M. It also means that sloppy
82imports (see above) can cause examples in external docstrings to use
83globals inappropriate for them.
84
85You can force use of your own dict as the execution context by passing
86"globs=your_dict" to testmod instead. Presumably this would be a copy of
87M.__dict__ merged with the globals from other imported modules.
88
89
Tim Peters8a7d2d52001-01-16 07:10:57 +000090WHAT ABOUT EXCEPTIONS?
91
92No problem, as long as the only output generated by the example is the
93traceback itself. For example:
94
Tim Peters60e23f42001-02-14 00:43:21 +000095 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +000096 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +000097 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +000098 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +000099 >>>
100
Tim Peters80e53142004-08-09 04:34:45 +0000101Note that only the exception type and value are compared.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000102
103
Tim Peters80e53142004-08-09 04:34:45 +0000104SO WHAT DOES A DOCTEST EXAMPLE LOOK LIKE ALREADY!?
Tim Peters8a7d2d52001-01-16 07:10:57 +0000105
106Oh ya. It's easy! In most cases a copy-and-paste of an interactive
107console session works fine -- just make sure the leading whitespace is
108rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
109right, but doctest is not in the business of guessing what you think a tab
110means).
111
112 >>> # comments are ignored
113 >>> x = 12
114 >>> x
115 12
116 >>> if x == 13:
117 ... print "yes"
118 ... else:
119 ... print "no"
120 ... print "NO"
121 ... print "NO!!!"
122 ...
123 no
124 NO
125 NO!!!
126 >>>
127
128Any expected output must immediately follow the final ">>>" or "..." line
129containing the code, and the expected output (if any) extends to the next
130">>>" or all-whitespace line. That's it.
131
132Bummers:
133
Tim Peters8a7d2d52001-01-16 07:10:57 +0000134+ Output to stdout is captured, but not output to stderr (exception
135 tracebacks are captured via a different means).
136
Martin v. Löwis92816de2004-05-31 19:01:00 +0000137+ If you continue a line via backslashing in an interactive session,
138 or for any other reason use a backslash, you should use a raw
139 docstring, which will preserve your backslahses exactly as you type
140 them:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000141
Tim Peters4e0e1b62004-07-07 20:54:48 +0000142 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000143 ... r'''Backslashes in a raw docstring: m\n'''
144 >>> print f.__doc__
145 Backslashes in a raw docstring: m\n
Tim Peters8a7d2d52001-01-16 07:10:57 +0000146
Martin v. Löwis92816de2004-05-31 19:01:00 +0000147 Otherwise, the backslash will be interpreted as part of the string.
148 E.g., the "\n" above would be interpreted as a newline character.
149 Alternatively, you can double each backslash in the doctest version
150 (and not use a raw string):
151
Tim Peters4e0e1b62004-07-07 20:54:48 +0000152 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000153 ... '''Backslashes in a raw docstring: m\\n'''
154 >>> print f.__doc__
155 Backslashes in a raw docstring: m\n
Tim Peters4e0e1b62004-07-07 20:54:48 +0000156
Tim Peters8a7d2d52001-01-16 07:10:57 +0000157The starting column doesn't matter:
158
159>>> assert "Easy!"
160 >>> import math
161 >>> math.floor(1.9)
162 1.0
163
164and as many leading whitespace characters are stripped from the expected
165output as appeared in the initial ">>>" line that triggered it.
166
167If you execute this very file, the examples above will be found and
Tim Peters80e53142004-08-09 04:34:45 +0000168executed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000169"""
Edward Loper8e4a34b2004-08-12 02:34:27 +0000170__docformat__ = 'reStructuredText en'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000171
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000172__all__ = [
Edward Loperb7503ff2004-08-19 19:19:03 +0000173 # 0, Option Flags
174 'register_optionflag',
175 'DONT_ACCEPT_TRUE_FOR_1',
176 'DONT_ACCEPT_BLANKLINE',
177 'NORMALIZE_WHITESPACE',
178 'ELLIPSIS',
179 'UNIFIED_DIFF',
180 'CONTEXT_DIFF',
Tim Petersc6cbab02004-08-22 19:43:28 +0000181 'NDIFF_DIFF',
Edward Loperb7503ff2004-08-19 19:19:03 +0000182 # 1. Utility Functions
Tim Peters8485b562004-08-04 18:46:34 +0000183 'is_private',
Edward Loperb7503ff2004-08-19 19:19:03 +0000184 # 2. Example & DocTest
Tim Peters8485b562004-08-04 18:46:34 +0000185 'Example',
186 'DocTest',
Edward Loperb7503ff2004-08-19 19:19:03 +0000187 # 3. Doctest Parser
188 'DocTestParser',
189 # 4. Doctest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000190 'DocTestFinder',
Edward Loperb7503ff2004-08-19 19:19:03 +0000191 # 5. Doctest Runner
Tim Peters8485b562004-08-04 18:46:34 +0000192 'DocTestRunner',
Edward Loperb7503ff2004-08-19 19:19:03 +0000193 'OutputChecker',
194 'DocTestFailure',
195 'UnexpectedException',
196 'DebugRunner',
197 # 6. Test Functions
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000198 'testmod',
199 'run_docstring_examples',
Edward Loperb7503ff2004-08-19 19:19:03 +0000200 # 7. Tester
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000201 'Tester',
Edward Loperb7503ff2004-08-19 19:19:03 +0000202 # 8. Unittest Support
Tim Peters19397e52004-08-06 22:02:59 +0000203 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000204 'DocTestSuite',
Edward Loperb7503ff2004-08-19 19:19:03 +0000205 'DocFileCase',
206 'DocFileTest',
207 'DocFileSuite',
208 # 9. Debugging Support
209 'script_from_examples',
Tim Petersdb3756d2003-06-29 05:30:48 +0000210 'testsource',
Edward Loperb7503ff2004-08-19 19:19:03 +0000211 'debug_src',
212 'debug_script',
Tim Petersdb3756d2003-06-29 05:30:48 +0000213 'debug',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000214]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000215
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000216import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000217
Tim Peters19397e52004-08-06 22:02:59 +0000218import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000219import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000220import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000221from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000222
Jim Fulton356fd192004-08-09 11:34:47 +0000223real_pdb_set_trace = pdb.set_trace
224
Tim Peters19397e52004-08-06 22:02:59 +0000225# There are 4 basic classes:
226# - Example: a <source, want> pair, plus an intra-docstring line number.
227# - DocTest: a collection of examples, parsed from a docstring, plus
228# info about where the docstring came from (name, filename, lineno).
229# - DocTestFinder: extracts DocTests from a given object's docstring and
230# its contained objects' docstrings.
231# - DocTestRunner: runs DocTest cases, and accumulates statistics.
232#
233# So the basic picture is:
234#
235# list of:
236# +------+ +---------+ +-------+
237# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
238# +------+ +---------+ +-------+
239# | Example |
240# | ... |
241# | Example |
242# +---------+
243
Edward Loperac20f572004-08-12 02:02:24 +0000244# Option constants.
245OPTIONFLAGS_BY_NAME = {}
246def register_optionflag(name):
247 flag = 1 << len(OPTIONFLAGS_BY_NAME)
248 OPTIONFLAGS_BY_NAME[name] = flag
249 return flag
250
251DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
252DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
253NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
254ELLIPSIS = register_optionflag('ELLIPSIS')
255UNIFIED_DIFF = register_optionflag('UNIFIED_DIFF')
256CONTEXT_DIFF = register_optionflag('CONTEXT_DIFF')
Tim Petersc6cbab02004-08-22 19:43:28 +0000257NDIFF_DIFF = register_optionflag('NDIFF_DIFF')
Edward Loperac20f572004-08-12 02:02:24 +0000258
259# Special string markers for use in `want` strings:
260BLANKLINE_MARKER = '<BLANKLINE>'
261ELLIPSIS_MARKER = '...'
262
Tim Peters8485b562004-08-04 18:46:34 +0000263######################################################################
264## Table of Contents
265######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000266# 1. Utility Functions
267# 2. Example & DocTest -- store test cases
268# 3. DocTest Parser -- extracts examples from strings
269# 4. DocTest Finder -- extracts test cases from objects
270# 5. DocTest Runner -- runs test cases
271# 6. Test Functions -- convenient wrappers for testing
272# 7. Tester Class -- for backwards compatibility
273# 8. Unittest Support
274# 9. Debugging Support
275# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000276
Tim Peters8485b562004-08-04 18:46:34 +0000277######################################################################
278## 1. Utility Functions
279######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000280
281def is_private(prefix, base):
282 """prefix, base -> true iff name prefix + "." + base is "private".
283
284 Prefix may be an empty string, and base does not contain a period.
285 Prefix is ignored (although functions you write conforming to this
286 protocol may make use of it).
287 Return true iff base begins with an (at least one) underscore, but
288 does not both begin and end with (at least) two underscores.
289
Tim Petersbafb1fe2004-08-08 01:52:57 +0000290 >>> warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
291 ... "doctest", 0)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000292 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000293 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000294 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000295 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000296 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000297 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000298 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000299 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000300 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000301 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000302 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000303 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000304 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000305 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000306 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000307 warnings.warn("is_private is deprecated; it wasn't useful; "
308 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000309 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000310 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
311
Tim Peters8485b562004-08-04 18:46:34 +0000312def _extract_future_flags(globs):
313 """
314 Return the compiler-flags associated with the future features that
315 have been imported into the given namespace (globs).
316 """
317 flags = 0
318 for fname in __future__.all_feature_names:
319 feature = globs.get(fname, None)
320 if feature is getattr(__future__, fname):
321 flags |= feature.compiler_flag
322 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000323
Tim Peters8485b562004-08-04 18:46:34 +0000324def _normalize_module(module, depth=2):
325 """
326 Return the module specified by `module`. In particular:
327 - If `module` is a module, then return module.
328 - If `module` is a string, then import and return the
329 module with that name.
330 - If `module` is None, then return the calling module.
331 The calling module is assumed to be the module of
332 the stack frame at the given depth in the call stack.
333 """
334 if inspect.ismodule(module):
335 return module
336 elif isinstance(module, (str, unicode)):
337 return __import__(module, globals(), locals(), ["*"])
338 elif module is None:
339 return sys.modules[sys._getframe(depth).f_globals['__name__']]
340 else:
341 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000342
Edward Lopera1ef6112004-08-09 16:14:41 +0000343def _tag_msg(tag, msg, indent=' '):
Tim Peters8485b562004-08-04 18:46:34 +0000344 """
345 Return a string that displays a tag-and-message pair nicely,
346 keeping the tag and its message on the same line when that
Edward Lopera1ef6112004-08-09 16:14:41 +0000347 makes sense. If the message is displayed on separate lines,
348 then `indent` is added to the beginning of each line.
Tim Peters8485b562004-08-04 18:46:34 +0000349 """
Tim Peters8485b562004-08-04 18:46:34 +0000350 # If the message doesn't end in a newline, then add one.
351 if msg[-1:] != '\n':
352 msg += '\n'
353 # If the message is short enough, and contains no internal
354 # newlines, then display it on the same line as the tag.
355 # Otherwise, display the tag on its own line.
356 if (len(tag) + len(msg) < 75 and
357 msg.find('\n', 0, len(msg)-1) == -1):
358 return '%s: %s' % (tag, msg)
359 else:
Edward Lopera1ef6112004-08-09 16:14:41 +0000360 msg = '\n'.join([indent+l for l in msg[:-1].split('\n')])
361 return '%s:\n%s\n' % (tag, msg)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000362
Edward Loper8e4a34b2004-08-12 02:34:27 +0000363def _exception_traceback(exc_info):
364 """
365 Return a string containing a traceback message for the given
366 exc_info tuple (as returned by sys.exc_info()).
367 """
368 # Get a traceback message.
369 excout = StringIO()
370 exc_type, exc_val, exc_tb = exc_info
371 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
372 return excout.getvalue()
373
Tim Peters8485b562004-08-04 18:46:34 +0000374# Override some StringIO methods.
375class _SpoofOut(StringIO):
376 def getvalue(self):
377 result = StringIO.getvalue(self)
378 # If anything at all was written, make sure there's a trailing
379 # newline. There's no way for the expected output to indicate
380 # that a trailing newline is missing.
381 if result and not result.endswith("\n"):
382 result += "\n"
383 # Prevent softspace from screwing up the next test case, in
384 # case they used print with a trailing comma in an example.
385 if hasattr(self, "softspace"):
386 del self.softspace
387 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000388
Tim Peters8485b562004-08-04 18:46:34 +0000389 def truncate(self, size=None):
390 StringIO.truncate(self, size)
391 if hasattr(self, "softspace"):
392 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000393
Tim Peters26b3ebb2004-08-19 08:10:08 +0000394# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000395def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000396 """
397 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000398 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000399 False
400 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000401 if ELLIPSIS_MARKER not in want:
402 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000403
Tim Peters26b3ebb2004-08-19 08:10:08 +0000404 # Find "the real" strings.
405 ws = want.split(ELLIPSIS_MARKER)
406 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000407
Tim Petersdc5de3b2004-08-19 14:06:20 +0000408 # Deal with exact matches possibly needed at one or both ends.
409 startpos, endpos = 0, len(got)
410 w = ws[0]
411 if w: # starts with exact match
412 if got.startswith(w):
413 startpos = len(w)
414 del ws[0]
415 else:
416 return False
417 w = ws[-1]
418 if w: # ends with exact match
419 if got.endswith(w):
420 endpos -= len(w)
421 del ws[-1]
422 else:
423 return False
424
425 if startpos > endpos:
426 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000427 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000428 return False
429
430 # For the rest, we only need to find the leftmost non-overlapping
431 # match for each piece. If there's no overall match that way alone,
432 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000433 for w in ws:
434 # w may be '' at times, if there are consecutive ellipses, or
435 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000436 # Search for an empty string succeeds, and doesn't change startpos.
437 startpos = got.find(w, startpos, endpos)
438 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000439 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000440 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000441
Tim Petersdc5de3b2004-08-19 14:06:20 +0000442 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000443
Tim Peters8485b562004-08-04 18:46:34 +0000444######################################################################
445## 2. Example & DocTest
446######################################################################
447## - An "example" is a <source, want> pair, where "source" is a
448## fragment of source code, and "want" is the expected output for
449## "source." The Example class also includes information about
450## where the example was extracted from.
451##
Edward Lopera1ef6112004-08-09 16:14:41 +0000452## - A "doctest" is a collection of examples, typically extracted from
453## a string (such as an object's docstring). The DocTest class also
454## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000455
Tim Peters8485b562004-08-04 18:46:34 +0000456class Example:
457 """
458 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000459 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000460
Edward Loper74bca7a2004-08-12 02:27:44 +0000461 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000462 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000463
Edward Loper74bca7a2004-08-12 02:27:44 +0000464 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000465 from stdout, or a traceback in case of exception). `want` ends
466 with a newline unless it's empty, in which case it's an empty
467 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000468
Edward Loper74bca7a2004-08-12 02:27:44 +0000469 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000470 this Example where the Example begins. This line number is
471 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000472
473 - indent: The example's indentation in the DocTest string.
474 I.e., the number of space characters that preceed the
475 example's first prompt.
476
477 - options: A dictionary mapping from option flags to True or
478 False, which is used to override default options for this
479 example. Any option flags not contained in this dictionary
480 are left at their default value (as specified by the
481 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000482 """
Edward Loper74bca7a2004-08-12 02:27:44 +0000483 def __init__(self, source, want, lineno, indent=0, options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000484 # Normalize inputs.
485 if not source.endswith('\n'):
486 source += '\n'
487 if want and not want.endswith('\n'):
488 want += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000489 # Store properties.
490 self.source = source
491 self.want = want
492 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000493 self.indent = indent
494 if options is None: options = {}
495 self.options = options
Tim Peters8a7d2d52001-01-16 07:10:57 +0000496
Tim Peters8485b562004-08-04 18:46:34 +0000497class DocTest:
498 """
499 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000500 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000501
Tim Peters8485b562004-08-04 18:46:34 +0000502 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000503
Tim Peters8485b562004-08-04 18:46:34 +0000504 - globs: The namespace (aka globals) that the examples should
505 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000506
Tim Peters8485b562004-08-04 18:46:34 +0000507 - name: A name identifying the DocTest (typically, the name of
508 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000509
Tim Peters8485b562004-08-04 18:46:34 +0000510 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000511 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000512
Tim Peters8485b562004-08-04 18:46:34 +0000513 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000514 begins, or `None` if the line number is unavailable. This
515 line number is zero-based, with respect to the beginning of
516 the file.
517
518 - docstring: The string that the examples were extracted from,
519 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000520 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000521 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000522 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000523 Create a new DocTest containing the given examples. The
524 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000525 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000526 assert not isinstance(examples, basestring), \
527 "DocTest no longer accepts str; use DocTestParser instead"
528 self.examples = examples
529 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000530 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000531 self.name = name
532 self.filename = filename
533 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000534
535 def __repr__(self):
536 if len(self.examples) == 0:
537 examples = 'no examples'
538 elif len(self.examples) == 1:
539 examples = '1 example'
540 else:
541 examples = '%d examples' % len(self.examples)
542 return ('<DocTest %s from %s:%s (%s)>' %
543 (self.name, self.filename, self.lineno, examples))
544
545
546 # This lets us sort tests by name:
547 def __cmp__(self, other):
548 if not isinstance(other, DocTest):
549 return -1
550 return cmp((self.name, self.filename, self.lineno, id(self)),
551 (other.name, other.filename, other.lineno, id(other)))
552
553######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000554## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000555######################################################################
556
Edward Lopera1ef6112004-08-09 16:14:41 +0000557class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000558 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000559 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000560 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000561 # This regular expression is used to find doctest examples in a
562 # string. It defines three groups: `source` is the source code
563 # (including leading indentation and prompts); `indent` is the
564 # indentation of the first (PS1) line of the source code; and
565 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000566 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000567 # Source consists of a PS1 line followed by zero or more PS2 lines.
568 (?P<source>
569 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
570 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
571 \n?
572 # Want consists of any non-blank lines that do not start with PS1.
573 (?P<want> (?:(?![ ]*$) # Not a blank line
574 (?![ ]*>>>) # Not a line starting with PS1
575 .*$\n? # But any other line
576 )*)
577 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000578
Tim Peters7ea48dd2004-08-13 01:52:59 +0000579 # A callable returning a true value iff its argument is a blank line
580 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000581 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000582
Edward Lopera1ef6112004-08-09 16:14:41 +0000583 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000584 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000585 Extract all doctest examples from the given string, and
586 collect them into a `DocTest` object.
587
588 `globs`, `name`, `filename`, and `lineno` are attributes for
589 the new `DocTest` object. See the documentation for `DocTest`
590 for more information.
591 """
592 return DocTest(self.get_examples(string, name), globs,
593 name, filename, lineno, string)
594
595 def get_examples(self, string, name='<string>'):
596 """
597 Extract all doctest examples from the given string, and return
598 them as a list of `Example` objects. Line numbers are
599 0-based, because it's most common in doctests that nothing
600 interesting appears on the same line as opening triple-quote,
601 and so the first interesting line is called \"line 1\" then.
602
603 The optional argument `name` is a name identifying this
604 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000605
606 >>> text = '''
607 ... >>> x, y = 2, 3 # no output expected
608 ... >>> if 1:
609 ... ... print x
610 ... ... print y
611 ... 2
612 ... 3
613 ...
614 ... Some text.
615 ... >>> x+y
616 ... 5
617 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000618 >>> for x in DocTestParser().get_examples(text):
Edward Loper78b58f32004-08-09 02:56:02 +0000619 ... print (x.source, x.want, x.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000620 ('x, y = 2, 3 # no output expected\\n', '', 1)
Edward Loper7c748462004-08-09 02:06:06 +0000621 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
Tim Petersbb431472004-08-09 03:51:46 +0000622 ('x+y\\n', '5\\n', 9)
Edward Loper7c748462004-08-09 02:06:06 +0000623 """
624 examples = []
625 charno, lineno = 0, 0
626 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000627 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000628 # Update lineno (lines before this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000629 lineno += string.count('\n', charno, m.start())
Edward Loper7c748462004-08-09 02:06:06 +0000630 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000631 (source, want) = self._parse_example(m, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000632 # Extract extra options from the source.
633 options = self._find_options(source, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000634 # Create an Example, and add it to the list.
Edward Loperb51b2342004-08-17 16:37:12 +0000635 if not self._IS_BLANK_OR_COMMENT(source):
636 examples.append( Example(source, want, lineno,
637 len(m.group('indent')), options) )
Edward Loper7c748462004-08-09 02:06:06 +0000638 # Update lineno (lines inside this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000639 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000640 # Update charno.
641 charno = m.end()
642 return examples
643
Edward Lopera1ef6112004-08-09 16:14:41 +0000644 def get_program(self, string, name="<string>"):
Edward Loper7c748462004-08-09 02:06:06 +0000645 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000646 Return an executable program from the given string, as a string.
Edward Loper7c748462004-08-09 02:06:06 +0000647
648 The format of this isn't rigidly defined. In general, doctest
649 examples become the executable statements in the result, and
650 their expected outputs become comments, preceded by an \"#Expected:\"
651 comment. Everything else (text, comments, everything not part of
652 a doctest test) is also placed in comments.
653
Edward Lopera1ef6112004-08-09 16:14:41 +0000654 The optional argument `name` is a name identifying this
655 string, and is only used for error messages.
656
Edward Loper7c748462004-08-09 02:06:06 +0000657 >>> text = '''
658 ... >>> x, y = 2, 3 # no output expected
659 ... >>> if 1:
660 ... ... print x
661 ... ... print y
662 ... 2
663 ... 3
664 ...
665 ... Some text.
666 ... >>> x+y
667 ... 5
668 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000669 >>> print DocTestParser().get_program(text)
Edward Loper7c748462004-08-09 02:06:06 +0000670 x, y = 2, 3 # no output expected
671 if 1:
672 print x
673 print y
674 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000675 ## 2
676 ## 3
Edward Loper7c748462004-08-09 02:06:06 +0000677 #
Edward Lopera5db6002004-08-12 02:41:30 +0000678 # Some text.
Edward Loper7c748462004-08-09 02:06:06 +0000679 x+y
680 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000681 ## 5
Edward Loper7c748462004-08-09 02:06:06 +0000682 """
Edward Lopera5db6002004-08-12 02:41:30 +0000683 string = string.expandtabs()
684 # If all lines begin with the same indentation, then strip it.
685 min_indent = self._min_indent(string)
686 if min_indent > 0:
687 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
688
Edward Loper7c748462004-08-09 02:06:06 +0000689 output = []
690 charnum, lineno = 0, 0
691 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000692 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000693 # Add any text before this example, as a comment.
694 if m.start() > charnum:
Edward Lopera1ef6112004-08-09 16:14:41 +0000695 lines = string[charnum:m.start()-1].split('\n')
Edward Loper7c748462004-08-09 02:06:06 +0000696 output.extend([self._comment_line(l) for l in lines])
697 lineno += len(lines)
698
699 # Extract source/want from the regexp match.
Edward Loper74bca7a2004-08-12 02:27:44 +0000700 (source, want) = self._parse_example(m, name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000701 # Display the source
702 output.append(source)
703 # Display the expected output, if any
704 if want:
705 output.append('# Expected:')
Edward Lopera5db6002004-08-12 02:41:30 +0000706 output.extend(['## '+l for l in want.split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000707
708 # Update the line number & char number.
Edward Lopera1ef6112004-08-09 16:14:41 +0000709 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000710 charnum = m.end()
711 # Add any remaining text, as comments.
712 output.extend([self._comment_line(l)
Edward Lopera1ef6112004-08-09 16:14:41 +0000713 for l in string[charnum:].split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000714 # Trim junk on both ends.
715 while output and output[-1] == '#':
716 output.pop()
717 while output and output[0] == '#':
718 output.pop(0)
719 # Combine the output, and return it.
720 return '\n'.join(output)
721
Edward Loper74bca7a2004-08-12 02:27:44 +0000722 def _parse_example(self, m, name, lineno):
723 """
724 Given a regular expression match from `_EXAMPLE_RE` (`m`),
725 return a pair `(source, want)`, where `source` is the matched
726 example's source code (with prompts and indentation stripped);
727 and `want` is the example's expected output (with indentation
728 stripped).
729
730 `name` is the string's name, and `lineno` is the line number
731 where the example starts; both are used for error messages.
732 """
Edward Loper7c748462004-08-09 02:06:06 +0000733 # Get the example's indentation level.
734 indent = len(m.group('indent'))
735
736 # Divide source into lines; check that they're properly
737 # indented; and then strip their indentation & prompts.
738 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000739 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000740 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000741 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000742
Tim Petersc5049152004-08-22 17:34:58 +0000743 # Divide want into lines; check that it's properly indented; and
744 # then strip the indentation. Spaces before the last newline should
745 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000746 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000747 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000748 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
749 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000750 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000751 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000752 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000753
754 return source, want
755
Edward Loper74bca7a2004-08-12 02:27:44 +0000756 # This regular expression looks for option directives in the
757 # source code of an example. Option directives are comments
758 # starting with "doctest:". Warning: this may give false
759 # positives for string-literals that contain the string
760 # "#doctest:". Eliminating these false positives would require
761 # actually parsing the string; but we limit them by ignoring any
762 # line containing "#doctest:" that is *followed* by a quote mark.
763 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
764 re.MULTILINE)
765
766 def _find_options(self, source, name, lineno):
767 """
768 Return a dictionary containing option overrides extracted from
769 option directives in the given source string.
770
771 `name` is the string's name, and `lineno` is the line number
772 where the example starts; both are used for error messages.
773 """
774 options = {}
775 # (note: with the current regexp, this will match at most once:)
776 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
777 option_strings = m.group(1).replace(',', ' ').split()
778 for option in option_strings:
779 if (option[0] not in '+-' or
780 option[1:] not in OPTIONFLAGS_BY_NAME):
781 raise ValueError('line %r of the doctest for %s '
782 'has an invalid option: %r' %
783 (lineno+1, name, option))
784 flag = OPTIONFLAGS_BY_NAME[option[1:]]
785 options[flag] = (option[0] == '+')
786 if options and self._IS_BLANK_OR_COMMENT(source):
787 raise ValueError('line %r of the doctest for %s has an option '
788 'directive on a line with no example: %r' %
789 (lineno, name, source))
790 return options
791
Edward Lopera5db6002004-08-12 02:41:30 +0000792 # This regular expression finds the indentation of every non-blank
793 # line in a string.
794 _INDENT_RE = re.compile('^([ ]+)(?=\S)', re.MULTILINE)
795
796 def _min_indent(self, s):
797 "Return the minimum indentation of any non-blank line in `s`"
798 return min([len(indent) for indent in self._INDENT_RE.findall(s)])
799
Edward Loper7c748462004-08-09 02:06:06 +0000800 def _comment_line(self, line):
Edward Loper74bca7a2004-08-12 02:27:44 +0000801 "Return a commented form of the given line"
Edward Loper7c748462004-08-09 02:06:06 +0000802 line = line.rstrip()
Tim Petersdd0e4752004-08-09 03:31:56 +0000803 if line:
Edward Lopera5db6002004-08-12 02:41:30 +0000804 return '# '+line
Tim Petersdd0e4752004-08-09 03:31:56 +0000805 else:
806 return '#'
Edward Loper7c748462004-08-09 02:06:06 +0000807
Edward Lopera1ef6112004-08-09 16:14:41 +0000808 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000809 """
810 Given the lines of a source string (including prompts and
811 leading indentation), check to make sure that every prompt is
812 followed by a space character. If any line is not followed by
813 a space character, then raise ValueError.
814 """
Edward Loper7c748462004-08-09 02:06:06 +0000815 for i, line in enumerate(lines):
816 if len(line) >= indent+4 and line[indent+3] != ' ':
817 raise ValueError('line %r of the docstring for %s '
818 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000819 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000820 line[indent:indent+3], line))
821
Edward Lopera1ef6112004-08-09 16:14:41 +0000822 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000823 """
824 Check that every line in the given list starts with the given
825 prefix; if any line does not, then raise a ValueError.
826 """
Edward Loper7c748462004-08-09 02:06:06 +0000827 for i, line in enumerate(lines):
828 if line and not line.startswith(prefix):
829 raise ValueError('line %r of the docstring for %s has '
830 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000831 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000832
833
834######################################################################
835## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000836######################################################################
837
838class DocTestFinder:
839 """
840 A class used to extract the DocTests that are relevant to a given
841 object, from its docstring and the docstrings of its contained
842 objects. Doctests can currently be extracted from the following
843 object types: modules, functions, classes, methods, staticmethods,
844 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000845 """
846
Edward Lopera1ef6112004-08-09 16:14:41 +0000847 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000848 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000849 """
850 Create a new doctest finder.
851
Edward Lopera1ef6112004-08-09 16:14:41 +0000852 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000853 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000854 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000855 signature for this factory function should match the signature
856 of the DocTest constructor.
857
Tim Peters8485b562004-08-04 18:46:34 +0000858 If the optional argument `recurse` is false, then `find` will
859 only examine the given object, and not any contained objects.
860 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000861 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000862 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000863 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000864 # _namefilter is undocumented, and exists only for temporary backward-
865 # compatibility support of testmod's deprecated isprivate mess.
866 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000867
868 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000869 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000870 """
871 Return a list of the DocTests that are defined by the given
872 object's docstring, or by any of its contained objects'
873 docstrings.
874
875 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000876 the given object. If the module is not specified or is None, then
877 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000878 correct module. The object's module is used:
879
880 - As a default namespace, if `globs` is not specified.
881 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000882 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000883 - To find the name of the file containing the object.
884 - To help find the line number of the object within its
885 file.
886
Tim Petersf3f57472004-08-08 06:11:48 +0000887 Contained objects whose module does not match `module` are ignored.
888
889 If `module` is False, no attempt to find the module will be made.
890 This is obscure, of use mostly in tests: if `module` is False, or
891 is None but cannot be found automatically, then all objects are
892 considered to belong to the (non-existent) module, so all contained
893 objects will (recursively) be searched for doctests.
894
Tim Peters8485b562004-08-04 18:46:34 +0000895 The globals for each DocTest is formed by combining `globs`
896 and `extraglobs` (bindings in `extraglobs` override bindings
897 in `globs`). A new copy of the globals dictionary is created
898 for each DocTest. If `globs` is not specified, then it
899 defaults to the module's `__dict__`, if specified, or {}
900 otherwise. If `extraglobs` is not specified, then it defaults
901 to {}.
902
Tim Peters8485b562004-08-04 18:46:34 +0000903 """
904 # If name was not specified, then extract it from the object.
905 if name is None:
906 name = getattr(obj, '__name__', None)
907 if name is None:
908 raise ValueError("DocTestFinder.find: name must be given "
909 "when obj.__name__ doesn't exist: %r" %
910 (type(obj),))
911
912 # Find the module that contains the given object (if obj is
913 # a module, then module=obj.). Note: this may fail, in which
914 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000915 if module is False:
916 module = None
917 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000918 module = inspect.getmodule(obj)
919
920 # Read the module's source code. This is used by
921 # DocTestFinder._find_lineno to find the line number for a
922 # given object's docstring.
923 try:
924 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
925 source_lines = linecache.getlines(file)
926 if not source_lines:
927 source_lines = None
928 except TypeError:
929 source_lines = None
930
931 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000932 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000933 if module is None:
934 globs = {}
935 else:
936 globs = module.__dict__.copy()
937 else:
938 globs = globs.copy()
939 if extraglobs is not None:
940 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000941
Tim Peters8485b562004-08-04 18:46:34 +0000942 # Recursively expore `obj`, extracting DocTests.
943 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000944 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000945 return tests
946
947 def _filter(self, obj, prefix, base):
948 """
949 Return true if the given object should not be examined.
950 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000951 return (self._namefilter is not None and
952 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000953
954 def _from_module(self, module, object):
955 """
956 Return true if the given object is defined in the given
957 module.
958 """
959 if module is None:
960 return True
961 elif inspect.isfunction(object):
962 return module.__dict__ is object.func_globals
963 elif inspect.isclass(object):
964 return module.__name__ == object.__module__
965 elif inspect.getmodule(object) is not None:
966 return module is inspect.getmodule(object)
967 elif hasattr(object, '__module__'):
968 return module.__name__ == object.__module__
969 elif isinstance(object, property):
970 return True # [XX] no way not be sure.
971 else:
972 raise ValueError("object must be a class or function")
973
Tim Petersf3f57472004-08-08 06:11:48 +0000974 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000975 """
976 Find tests for the given object and any contained objects, and
977 add them to `tests`.
978 """
979 if self._verbose:
980 print 'Finding tests in %s' % name
981
982 # If we've already processed this object, then ignore it.
983 if id(obj) in seen:
984 return
985 seen[id(obj)] = 1
986
987 # Find a test for this object, and add it to the list of tests.
988 test = self._get_test(obj, name, module, globs, source_lines)
989 if test is not None:
990 tests.append(test)
991
992 # Look for tests in a module's contained objects.
993 if inspect.ismodule(obj) and self._recurse:
994 for valname, val in obj.__dict__.items():
995 # Check if this contained object should be ignored.
996 if self._filter(val, name, valname):
997 continue
998 valname = '%s.%s' % (name, valname)
999 # Recurse to functions & classes.
1000 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +00001001 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001002 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001003 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001004
1005 # Look for tests in a module's __test__ dictionary.
1006 if inspect.ismodule(obj) and self._recurse:
1007 for valname, val in getattr(obj, '__test__', {}).items():
1008 if not isinstance(valname, basestring):
1009 raise ValueError("DocTestFinder.find: __test__ keys "
1010 "must be strings: %r" %
1011 (type(valname),))
1012 if not (inspect.isfunction(val) or inspect.isclass(val) or
1013 inspect.ismethod(val) or inspect.ismodule(val) or
1014 isinstance(val, basestring)):
1015 raise ValueError("DocTestFinder.find: __test__ values "
1016 "must be strings, functions, methods, "
1017 "classes, or modules: %r" %
1018 (type(val),))
1019 valname = '%s.%s' % (name, valname)
1020 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001021 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001022
1023 # Look for tests in a class's contained objects.
1024 if inspect.isclass(obj) and self._recurse:
1025 for valname, val in obj.__dict__.items():
1026 # Check if this contained object should be ignored.
1027 if self._filter(val, name, valname):
1028 continue
1029 # Special handling for staticmethod/classmethod.
1030 if isinstance(val, staticmethod):
1031 val = getattr(obj, valname)
1032 if isinstance(val, classmethod):
1033 val = getattr(obj, valname).im_func
1034
1035 # Recurse to methods, properties, and nested classes.
1036 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001037 isinstance(val, property)) and
1038 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001039 valname = '%s.%s' % (name, valname)
1040 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001041 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001042
1043 def _get_test(self, obj, name, module, globs, source_lines):
1044 """
1045 Return a DocTest for the given object, if it defines a docstring;
1046 otherwise, return None.
1047 """
1048 # Extract the object's docstring. If it doesn't have one,
1049 # then return None (no test for this object).
1050 if isinstance(obj, basestring):
1051 docstring = obj
1052 else:
1053 try:
1054 if obj.__doc__ is None:
1055 return None
1056 docstring = str(obj.__doc__)
1057 except (TypeError, AttributeError):
1058 return None
1059
1060 # Don't bother if the docstring is empty.
1061 if not docstring:
1062 return None
1063
1064 # Find the docstring's location in the file.
1065 lineno = self._find_lineno(obj, source_lines)
1066
1067 # Return a DocTest for this object.
1068 if module is None:
1069 filename = None
1070 else:
1071 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001072 if filename[-4:] in (".pyc", ".pyo"):
1073 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001074 return self._parser.get_doctest(docstring, globs, name,
1075 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001076
1077 def _find_lineno(self, obj, source_lines):
1078 """
1079 Return a line number of the given object's docstring. Note:
1080 this method assumes that the object has a docstring.
1081 """
1082 lineno = None
1083
1084 # Find the line number for modules.
1085 if inspect.ismodule(obj):
1086 lineno = 0
1087
1088 # Find the line number for classes.
1089 # Note: this could be fooled if a class is defined multiple
1090 # times in a single file.
1091 if inspect.isclass(obj):
1092 if source_lines is None:
1093 return None
1094 pat = re.compile(r'^\s*class\s*%s\b' %
1095 getattr(obj, '__name__', '-'))
1096 for i, line in enumerate(source_lines):
1097 if pat.match(line):
1098 lineno = i
1099 break
1100
1101 # Find the line number for functions & methods.
1102 if inspect.ismethod(obj): obj = obj.im_func
1103 if inspect.isfunction(obj): obj = obj.func_code
1104 if inspect.istraceback(obj): obj = obj.tb_frame
1105 if inspect.isframe(obj): obj = obj.f_code
1106 if inspect.iscode(obj):
1107 lineno = getattr(obj, 'co_firstlineno', None)-1
1108
1109 # Find the line number where the docstring starts. Assume
1110 # that it's the first line that begins with a quote mark.
1111 # Note: this could be fooled by a multiline function
1112 # signature, where a continuation line begins with a quote
1113 # mark.
1114 if lineno is not None:
1115 if source_lines is None:
1116 return lineno+1
1117 pat = re.compile('(^|.*:)\s*\w*("|\')')
1118 for lineno in range(lineno, len(source_lines)):
1119 if pat.match(source_lines[lineno]):
1120 return lineno
1121
1122 # We couldn't find the line number.
1123 return None
1124
1125######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001126## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001127######################################################################
1128
Tim Peters8485b562004-08-04 18:46:34 +00001129class DocTestRunner:
1130 """
1131 A class used to run DocTest test cases, and accumulate statistics.
1132 The `run` method is used to process a single DocTest case. It
1133 returns a tuple `(f, t)`, where `t` is the number of test cases
1134 tried, and `f` is the number of test cases that failed.
1135
1136 >>> tests = DocTestFinder().find(_TestClass)
1137 >>> runner = DocTestRunner(verbose=False)
1138 >>> for test in tests:
1139 ... print runner.run(test)
1140 (0, 2)
1141 (0, 1)
1142 (0, 2)
1143 (0, 2)
1144
1145 The `summarize` method prints a summary of all the test cases that
1146 have been run by the runner, and returns an aggregated `(f, t)`
1147 tuple:
1148
1149 >>> runner.summarize(verbose=1)
1150 4 items passed all tests:
1151 2 tests in _TestClass
1152 2 tests in _TestClass.__init__
1153 2 tests in _TestClass.get
1154 1 tests in _TestClass.square
1155 7 tests in 4 items.
1156 7 passed and 0 failed.
1157 Test passed.
1158 (0, 7)
1159
1160 The aggregated number of tried examples and failed examples is
1161 also available via the `tries` and `failures` attributes:
1162
1163 >>> runner.tries
1164 7
1165 >>> runner.failures
1166 0
1167
1168 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001169 by an `OutputChecker`. This comparison may be customized with a
1170 number of option flags; see the documentation for `testmod` for
1171 more information. If the option flags are insufficient, then the
1172 comparison may also be customized by passing a subclass of
1173 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001174
1175 The test runner's display output can be controlled in two ways.
1176 First, an output function (`out) can be passed to
1177 `TestRunner.run`; this function will be called with strings that
1178 should be displayed. It defaults to `sys.stdout.write`. If
1179 capturing the output is not sufficient, then the display output
1180 can be also customized by subclassing DocTestRunner, and
1181 overriding the methods `report_start`, `report_success`,
1182 `report_unexpected_exception`, and `report_failure`.
1183 """
1184 # This divider string is used to separate failure messages, and to
1185 # separate sections of the summary.
1186 DIVIDER = "*" * 70
1187
Edward Loper34fcb142004-08-09 02:45:41 +00001188 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001189 """
1190 Create a new test runner.
1191
Edward Loper34fcb142004-08-09 02:45:41 +00001192 Optional keyword arg `checker` is the `OutputChecker` that
1193 should be used to compare the expected outputs and actual
1194 outputs of doctest examples.
1195
Tim Peters8485b562004-08-04 18:46:34 +00001196 Optional keyword arg 'verbose' prints lots of stuff if true,
1197 only failures if false; by default, it's true iff '-v' is in
1198 sys.argv.
1199
1200 Optional argument `optionflags` can be used to control how the
1201 test runner compares expected output to actual output, and how
1202 it displays failures. See the documentation for `testmod` for
1203 more information.
1204 """
Edward Loper34fcb142004-08-09 02:45:41 +00001205 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001206 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001207 verbose = '-v' in sys.argv
1208 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001209 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001210 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001211
Tim Peters8485b562004-08-04 18:46:34 +00001212 # Keep track of the examples we've run.
1213 self.tries = 0
1214 self.failures = 0
1215 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001216
Tim Peters8485b562004-08-04 18:46:34 +00001217 # Create a fake output target for capturing doctest output.
1218 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001219
Tim Peters8485b562004-08-04 18:46:34 +00001220 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001221 # Reporting methods
1222 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001223
Tim Peters8485b562004-08-04 18:46:34 +00001224 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001225 """
Tim Peters8485b562004-08-04 18:46:34 +00001226 Report that the test runner is about to process the given
1227 example. (Only displays a message if verbose=True)
1228 """
1229 if self._verbose:
1230 out(_tag_msg("Trying", example.source) +
1231 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001232
Tim Peters8485b562004-08-04 18:46:34 +00001233 def report_success(self, out, test, example, got):
1234 """
1235 Report that the given example ran successfully. (Only
1236 displays a message if verbose=True)
1237 """
1238 if self._verbose:
1239 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001240
Tim Peters8485b562004-08-04 18:46:34 +00001241 def report_failure(self, out, test, example, got):
1242 """
1243 Report that the given example failed.
1244 """
1245 # Print an error message.
Edward Loper8e4a34b2004-08-12 02:34:27 +00001246 out(self._failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001247 self._checker.output_difference(example.want, got,
1248 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001249
Tim Peters8485b562004-08-04 18:46:34 +00001250 def report_unexpected_exception(self, out, test, example, exc_info):
1251 """
1252 Report that the given example raised an unexpected exception.
1253 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001254 out(self._failure_header(test, example) +
1255 _tag_msg("Exception raised", _exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001256
Edward Loper8e4a34b2004-08-12 02:34:27 +00001257 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001258 out = [self.DIVIDER]
1259 if test.filename:
1260 if test.lineno is not None and example.lineno is not None:
1261 lineno = test.lineno + example.lineno + 1
1262 else:
1263 lineno = '?'
1264 out.append('File "%s", line %s, in %s' %
1265 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001266 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001267 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1268 out.append('Failed example:')
1269 source = example.source
1270 if source.endswith('\n'):
1271 source = source[:-1]
1272 out.append(' ' + '\n '.join(source.split('\n')))
1273 return '\n'.join(out)+'\n'
Tim Peters7402f792001-10-02 03:53:41 +00001274
Tim Peters8485b562004-08-04 18:46:34 +00001275 #/////////////////////////////////////////////////////////////////
1276 # DocTest Running
1277 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001278
Tim Peters8485b562004-08-04 18:46:34 +00001279 # A regular expression for handling `want` strings that contain
Tim Peters41a65ea2004-08-13 03:55:05 +00001280 # expected exceptions. It divides `want` into three pieces:
1281 # - the pre-exception output (`want`)
1282 # - the traceback header line (`hdr`)
1283 # - the exception message (`msg`), as generated by
1284 # traceback.format_exception_only()
1285 # `msg` may have multiple lines. We assume/require that the
1286 # exception message is the first non-indented line starting with a word
1287 # character following the traceback header line.
1288 _EXCEPTION_RE = re.compile(r"""
1289 (?P<want> .*?) # suck up everything until traceback header
1290 # Grab the traceback header. Different versions of Python have
1291 # said different things on the first traceback line.
1292 ^(?P<hdr> Traceback\ \(
1293 (?: most\ recent\ call\ last
1294 | innermost\ last
1295 ) \) :
1296 )
1297 \s* $ # toss trailing whitespace on traceback header
1298 .*? # don't blink: absorb stuff until a line *starts* with \w
1299 ^ (?P<msg> \w+ .*)
1300 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001301
Tim Peters8485b562004-08-04 18:46:34 +00001302 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001303 """
Tim Peters8485b562004-08-04 18:46:34 +00001304 Run the examples in `test`. Write the outcome of each example
1305 with one of the `DocTestRunner.report_*` methods, using the
1306 writer function `out`. `compileflags` is the set of compiler
1307 flags that should be used to execute examples. Return a tuple
1308 `(f, t)`, where `t` is the number of examples tried, and `f`
1309 is the number of examples that failed. The examples are run
1310 in the namespace `test.globs`.
1311 """
1312 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001313 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001314
1315 # Save the option flags (since option directives can be used
1316 # to modify them).
1317 original_optionflags = self.optionflags
1318
1319 # Process each example.
1320 for example in test.examples:
Edward Loper74bca7a2004-08-12 02:27:44 +00001321 # Merge in the example's options.
1322 self.optionflags = original_optionflags
1323 if example.options:
1324 for (optionflag, val) in example.options.items():
1325 if val:
1326 self.optionflags |= optionflag
1327 else:
1328 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001329
1330 # Record that we started this example.
1331 tries += 1
1332 self.report_start(out, test, example)
1333
1334 # Run the example in the given context (globs), and record
1335 # any exception that gets raised. (But don't intercept
1336 # keyboard interrupts.)
1337 try:
Tim Peters208ca702004-08-09 04:12:36 +00001338 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001339 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001340 compileflags, 1) in test.globs
1341 exception = None
1342 except KeyboardInterrupt:
1343 raise
1344 except:
1345 exception = sys.exc_info()
1346
Tim Peters208ca702004-08-09 04:12:36 +00001347 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001348 self._fakeout.truncate(0)
1349
1350 # If the example executed without raising any exceptions,
1351 # then verify its output and report its outcome.
1352 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001353 if self._checker.check_output(example.want, got,
1354 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001355 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001356 else:
Tim Peters8485b562004-08-04 18:46:34 +00001357 self.report_failure(out, test, example, got)
1358 failures += 1
1359
1360 # If the example raised an exception, then check if it was
1361 # expected.
1362 else:
1363 exc_info = sys.exc_info()
1364 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1365
1366 # Search the `want` string for an exception. If we don't
1367 # find one, then report an unexpected exception.
1368 m = self._EXCEPTION_RE.match(example.want)
1369 if m is None:
1370 self.report_unexpected_exception(out, test, example,
1371 exc_info)
1372 failures += 1
1373 else:
Tim Peters41a65ea2004-08-13 03:55:05 +00001374 e_want, e_msg = m.group('want', 'msg')
Tim Peters8485b562004-08-04 18:46:34 +00001375 # The test passes iff the pre-exception output and
1376 # the exception description match the values given
1377 # in `want`.
Tim Peters41a65ea2004-08-13 03:55:05 +00001378 if (self._checker.check_output(e_want, got,
Edward Loper34fcb142004-08-09 02:45:41 +00001379 self.optionflags) and
Tim Peters41a65ea2004-08-13 03:55:05 +00001380 self._checker.check_output(e_msg, exc_msg,
Edward Loper34fcb142004-08-09 02:45:41 +00001381 self.optionflags)):
Tim Peters8485b562004-08-04 18:46:34 +00001382 self.report_success(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001383 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001384 else:
1385 self.report_failure(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001386 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001387 failures += 1
1388
1389 # Restore the option flags (in case they were modified)
1390 self.optionflags = original_optionflags
1391
1392 # Record and return the number of failures and tries.
1393 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001394 return failures, tries
1395
Tim Peters8485b562004-08-04 18:46:34 +00001396 def __record_outcome(self, test, f, t):
1397 """
1398 Record the fact that the given DocTest (`test`) generated `f`
1399 failures out of `t` tried examples.
1400 """
1401 f2, t2 = self._name2ft.get(test.name, (0,0))
1402 self._name2ft[test.name] = (f+f2, t+t2)
1403 self.failures += f
1404 self.tries += t
1405
1406 def run(self, test, compileflags=None, out=None, clear_globs=True):
1407 """
1408 Run the examples in `test`, and display the results using the
1409 writer function `out`.
1410
1411 The examples are run in the namespace `test.globs`. If
1412 `clear_globs` is true (the default), then this namespace will
1413 be cleared after the test runs, to help with garbage
1414 collection. If you would like to examine the namespace after
1415 the test completes, then use `clear_globs=False`.
1416
1417 `compileflags` gives the set of flags that should be used by
1418 the Python compiler when running the examples. If not
1419 specified, then it will default to the set of future-import
1420 flags that apply to `globs`.
1421
1422 The output of each example is checked using
1423 `DocTestRunner.check_output`, and the results are formatted by
1424 the `DocTestRunner.report_*` methods.
1425 """
1426 if compileflags is None:
1427 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001428
Tim Peters6c542b72004-08-09 16:43:36 +00001429 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001430 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001431 out = save_stdout.write
1432 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001433
Tim Peters6c542b72004-08-09 16:43:36 +00001434 # Patch pdb.set_trace to restore sys.stdout, so that interactive
1435 # debugging output is visible (not still redirected to self._fakeout).
1436 # Note that we run "the real" pdb.set_trace (captured at doctest
1437 # import time) in our replacement. Because the current run() may
1438 # run another doctest (and so on), the current pdb.set_trace may be
1439 # our set_trace function, which changes sys.stdout. If we called
1440 # a chain of those, we wouldn't be left with the save_stdout
1441 # *this* run() invocation wants.
Jim Fulton356fd192004-08-09 11:34:47 +00001442 def set_trace():
Tim Peters6c542b72004-08-09 16:43:36 +00001443 sys.stdout = save_stdout
Jim Fulton356fd192004-08-09 11:34:47 +00001444 real_pdb_set_trace()
1445
Tim Peters6c542b72004-08-09 16:43:36 +00001446 save_set_trace = pdb.set_trace
1447 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001448 try:
Tim Peters8485b562004-08-04 18:46:34 +00001449 return self.__run(test, compileflags, out)
1450 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001451 sys.stdout = save_stdout
1452 pdb.set_trace = save_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001453 if clear_globs:
1454 test.globs.clear()
1455
1456 #/////////////////////////////////////////////////////////////////
1457 # Summarization
1458 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001459 def summarize(self, verbose=None):
1460 """
Tim Peters8485b562004-08-04 18:46:34 +00001461 Print a summary of all the test cases that have been run by
1462 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1463 the total number of failed examples, and `t` is the total
1464 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001465
Tim Peters8485b562004-08-04 18:46:34 +00001466 The optional `verbose` argument controls how detailed the
1467 summary is. If the verbosity is not specified, then the
1468 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001469 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001470 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001471 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001472 notests = []
1473 passed = []
1474 failed = []
1475 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001476 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001477 name, (f, t) = x
1478 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001479 totalt += t
1480 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001481 if t == 0:
1482 notests.append(name)
1483 elif f == 0:
1484 passed.append( (name, t) )
1485 else:
1486 failed.append(x)
1487 if verbose:
1488 if notests:
1489 print len(notests), "items had no tests:"
1490 notests.sort()
1491 for thing in notests:
1492 print " ", thing
1493 if passed:
1494 print len(passed), "items passed all tests:"
1495 passed.sort()
1496 for thing, count in passed:
1497 print " %3d tests in %s" % (count, thing)
1498 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001499 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001500 print len(failed), "items had failures:"
1501 failed.sort()
1502 for thing, (f, t) in failed:
1503 print " %3d of %3d in %s" % (f, t, thing)
1504 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001505 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001506 print totalt - totalf, "passed and", totalf, "failed."
1507 if totalf:
1508 print "***Test Failed***", totalf, "failures."
1509 elif verbose:
1510 print "Test passed."
1511 return totalf, totalt
1512
Edward Loper34fcb142004-08-09 02:45:41 +00001513class OutputChecker:
1514 """
1515 A class used to check the whether the actual output from a doctest
1516 example matches the expected output. `OutputChecker` defines two
1517 methods: `check_output`, which compares a given pair of outputs,
1518 and returns true if they match; and `output_difference`, which
1519 returns a string describing the differences between two outputs.
1520 """
1521 def check_output(self, want, got, optionflags):
1522 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001523 Return True iff the actual output from an example (`got`)
1524 matches the expected output (`want`). These strings are
1525 always considered to match if they are identical; but
1526 depending on what option flags the test runner is using,
1527 several non-exact match types are also possible. See the
1528 documentation for `TestRunner` for more information about
1529 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001530 """
1531 # Handle the common case first, for efficiency:
1532 # if they're string-identical, always return true.
1533 if got == want:
1534 return True
1535
1536 # The values True and False replaced 1 and 0 as the return
1537 # value for boolean comparisons in Python 2.3.
1538 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1539 if (got,want) == ("True\n", "1\n"):
1540 return True
1541 if (got,want) == ("False\n", "0\n"):
1542 return True
1543
1544 # <BLANKLINE> can be used as a special sequence to signify a
1545 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1546 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1547 # Replace <BLANKLINE> in want with a blank line.
1548 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1549 '', want)
1550 # If a line in got contains only spaces, then remove the
1551 # spaces.
1552 got = re.sub('(?m)^\s*?$', '', got)
1553 if got == want:
1554 return True
1555
1556 # This flag causes doctest to ignore any differences in the
1557 # contents of whitespace strings. Note that this can be used
1558 # in conjunction with the ELLISPIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001559 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001560 got = ' '.join(got.split())
1561 want = ' '.join(want.split())
1562 if got == want:
1563 return True
1564
1565 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001566 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001567 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001568 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001569 return True
1570
1571 # We didn't find any match; return false.
1572 return False
1573
Tim Petersc6cbab02004-08-22 19:43:28 +00001574 # Should we do a fancy diff?
1575 def _do_a_fancy_diff(self, want, got, optionflags):
1576 # Not unless they asked for a fancy diff.
1577 if not optionflags & (UNIFIED_DIFF |
1578 CONTEXT_DIFF |
1579 NDIFF_DIFF):
1580 return False
1581 # If expected output uses ellipsis, a meaningful fancy diff is
1582 # too hard.
1583 if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1584 return False
1585 # ndiff does intraline difference marking, so can be useful even
1586 # for 1-line inputs.
1587 if optionflags & NDIFF_DIFF:
1588 return True
1589 # The other diff types need at least a few lines to be helpful.
1590 return want.count('\n') > 2 and got.count('\n') > 2
1591
Edward Loper34fcb142004-08-09 02:45:41 +00001592 def output_difference(self, want, got, optionflags):
1593 """
1594 Return a string describing the differences between the
Edward Loper74bca7a2004-08-12 02:27:44 +00001595 expected output for an example (`want`) and the actual output
1596 (`got`). `optionflags` is the set of option flags used to
1597 compare `want` and `got`. `indent` is the indentation of the
1598 original example.
Edward Loper34fcb142004-08-09 02:45:41 +00001599 """
Tim Petersc5049152004-08-22 17:34:58 +00001600
Edward Loper68ba9a62004-08-12 02:43:49 +00001601 # If <BLANKLINE>s are being used, then replace blank lines
1602 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001603 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001604 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001605
1606 # Check if we should use diff. Don't use diff if the actual
1607 # or expected outputs are too short, or if the expected output
1608 # contains an ellipsis marker.
Tim Petersc6cbab02004-08-22 19:43:28 +00001609 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001610 # Split want & got into lines.
1611 want_lines = [l+'\n' for l in want.split('\n')]
1612 got_lines = [l+'\n' for l in got.split('\n')]
1613 # Use difflib to find their differences.
1614 if optionflags & UNIFIED_DIFF:
1615 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1616 fromfile='Expected', tofile='Got')
Tim Petersc6cbab02004-08-22 19:43:28 +00001617 kind = 'unified diff'
Edward Loper34fcb142004-08-09 02:45:41 +00001618 elif optionflags & CONTEXT_DIFF:
1619 diff = difflib.context_diff(want_lines, got_lines, n=2,
1620 fromfile='Expected', tofile='Got')
Tim Petersc6cbab02004-08-22 19:43:28 +00001621 kind = 'context diff'
1622 elif optionflags & NDIFF_DIFF:
1623 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1624 diff = list(engine.compare(want_lines, got_lines))
1625 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001626 else:
1627 assert 0, 'Bad diff option'
1628 # Remove trailing whitespace on diff output.
1629 diff = [line.rstrip() + '\n' for line in diff]
Tim Petersc6cbab02004-08-22 19:43:28 +00001630 return _tag_msg("Differences (" + kind + ")",
Edward Loper34fcb142004-08-09 02:45:41 +00001631 ''.join(diff))
1632
1633 # If we're not using diff, then simply list the expected
1634 # output followed by the actual output.
Jim Fulton07a349c2004-08-22 14:10:00 +00001635 if want.endswith('\n'):
1636 want = want[:-1]
1637 want = ' ' + '\n '.join(want.split('\n'))
1638 if got.endswith('\n'):
1639 got = got[:-1]
1640 got = ' ' + '\n '.join(got.split('\n'))
1641 return "Expected:\n%s\nGot:\n%s\n" % (want, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001642
Tim Peters19397e52004-08-06 22:02:59 +00001643class DocTestFailure(Exception):
1644 """A DocTest example has failed in debugging mode.
1645
1646 The exception instance has variables:
1647
1648 - test: the DocTest object being run
1649
1650 - excample: the Example object that failed
1651
1652 - got: the actual output
1653 """
1654 def __init__(self, test, example, got):
1655 self.test = test
1656 self.example = example
1657 self.got = got
1658
1659 def __str__(self):
1660 return str(self.test)
1661
1662class UnexpectedException(Exception):
1663 """A DocTest example has encountered an unexpected exception
1664
1665 The exception instance has variables:
1666
1667 - test: the DocTest object being run
1668
1669 - excample: the Example object that failed
1670
1671 - exc_info: the exception info
1672 """
1673 def __init__(self, test, example, exc_info):
1674 self.test = test
1675 self.example = example
1676 self.exc_info = exc_info
1677
1678 def __str__(self):
1679 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001680
Tim Peters19397e52004-08-06 22:02:59 +00001681class DebugRunner(DocTestRunner):
1682 r"""Run doc tests but raise an exception as soon as there is a failure.
1683
1684 If an unexpected exception occurs, an UnexpectedException is raised.
1685 It contains the test, the example, and the original exception:
1686
1687 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001688 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1689 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001690 >>> try:
1691 ... runner.run(test)
1692 ... except UnexpectedException, failure:
1693 ... pass
1694
1695 >>> failure.test is test
1696 True
1697
1698 >>> failure.example.want
1699 '42\n'
1700
1701 >>> exc_info = failure.exc_info
1702 >>> raise exc_info[0], exc_info[1], exc_info[2]
1703 Traceback (most recent call last):
1704 ...
1705 KeyError
1706
1707 We wrap the original exception to give the calling application
1708 access to the test and example information.
1709
1710 If the output doesn't match, then a DocTestFailure is raised:
1711
Edward Lopera1ef6112004-08-09 16:14:41 +00001712 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001713 ... >>> x = 1
1714 ... >>> x
1715 ... 2
1716 ... ''', {}, 'foo', 'foo.py', 0)
1717
1718 >>> try:
1719 ... runner.run(test)
1720 ... except DocTestFailure, failure:
1721 ... pass
1722
1723 DocTestFailure objects provide access to the test:
1724
1725 >>> failure.test is test
1726 True
1727
1728 As well as to the example:
1729
1730 >>> failure.example.want
1731 '2\n'
1732
1733 and the actual output:
1734
1735 >>> failure.got
1736 '1\n'
1737
1738 If a failure or error occurs, the globals are left intact:
1739
1740 >>> del test.globs['__builtins__']
1741 >>> test.globs
1742 {'x': 1}
1743
Edward Lopera1ef6112004-08-09 16:14:41 +00001744 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001745 ... >>> x = 2
1746 ... >>> raise KeyError
1747 ... ''', {}, 'foo', 'foo.py', 0)
1748
1749 >>> runner.run(test)
1750 Traceback (most recent call last):
1751 ...
1752 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001753
Tim Peters19397e52004-08-06 22:02:59 +00001754 >>> del test.globs['__builtins__']
1755 >>> test.globs
1756 {'x': 2}
1757
1758 But the globals are cleared if there is no error:
1759
Edward Lopera1ef6112004-08-09 16:14:41 +00001760 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001761 ... >>> x = 2
1762 ... ''', {}, 'foo', 'foo.py', 0)
1763
1764 >>> runner.run(test)
1765 (0, 1)
1766
1767 >>> test.globs
1768 {}
1769
1770 """
1771
1772 def run(self, test, compileflags=None, out=None, clear_globs=True):
1773 r = DocTestRunner.run(self, test, compileflags, out, False)
1774 if clear_globs:
1775 test.globs.clear()
1776 return r
1777
1778 def report_unexpected_exception(self, out, test, example, exc_info):
1779 raise UnexpectedException(test, example, exc_info)
1780
1781 def report_failure(self, out, test, example, got):
1782 raise DocTestFailure(test, example, got)
1783
Tim Peters8485b562004-08-04 18:46:34 +00001784######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001785## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001786######################################################################
1787# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001788
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001789def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001790 report=True, optionflags=0, extraglobs=None,
1791 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001792 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001793 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001794
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001795 Test examples in docstrings in functions and classes reachable
1796 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001797 with m.__doc__. Unless isprivate is specified, private names
1798 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001799
1800 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001801 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001802 function and class docstrings are tested even if the name is private;
1803 strings are tested directly, as if they were docstrings.
1804
1805 Return (#failures, #tests).
1806
1807 See doctest.__doc__ for an overview.
1808
1809 Optional keyword arg "name" gives the name of the module; by default
1810 use m.__name__.
1811
1812 Optional keyword arg "globs" gives a dict to be used as the globals
1813 when executing examples; by default, use m.__dict__. A copy of this
1814 dict is actually used for each docstring, so that each docstring's
1815 examples start with a clean slate.
1816
Tim Peters8485b562004-08-04 18:46:34 +00001817 Optional keyword arg "extraglobs" gives a dictionary that should be
1818 merged into the globals that are used to execute examples. By
1819 default, no extra globals are used. This is new in 2.4.
1820
Tim Peters8a7d2d52001-01-16 07:10:57 +00001821 Optional keyword arg "verbose" prints lots of stuff if true, prints
1822 only failures if false; by default, it's true iff "-v" is in sys.argv.
1823
Tim Peters8a7d2d52001-01-16 07:10:57 +00001824 Optional keyword arg "report" prints a summary at the end when true,
1825 else prints nothing at the end. In verbose mode, the summary is
1826 detailed, else very brief (in fact, empty if all tests passed).
1827
Tim Peters6ebe61f2003-06-27 20:48:05 +00001828 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001829 and defaults to 0. This is new in 2.3. Possible values (see the
1830 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001831
1832 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001833 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001834 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001835 ELLIPSIS
Tim Peters8485b562004-08-04 18:46:34 +00001836 UNIFIED_DIFF
Tim Peters8485b562004-08-04 18:46:34 +00001837 CONTEXT_DIFF
Tim Petersf82a9de2004-08-22 20:51:53 +00001838 NDIFF_DIFF
Tim Peters19397e52004-08-06 22:02:59 +00001839
1840 Optional keyword arg "raise_on_error" raises an exception on the
1841 first unexpected exception or failure. This allows failures to be
1842 post-mortem debugged.
1843
Tim Petersf727c6c2004-08-08 01:48:59 +00001844 Deprecated in Python 2.4:
1845 Optional keyword arg "isprivate" specifies a function used to
1846 determine whether a name is private. The default function is
1847 treat all functions as public. Optionally, "isprivate" can be
1848 set to doctest.is_private to skip over functions marked as private
1849 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001850 """
1851
1852 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001853 Advanced tomfoolery: testmod runs methods of a local instance of
1854 class doctest.Tester, then merges the results into (or creates)
1855 global Tester instance doctest.master. Methods of doctest.master
1856 can be called directly too, if you want to do something unusual.
1857 Passing report=0 to testmod is especially useful then, to delay
1858 displaying a summary. Invoke doctest.master.summarize(verbose)
1859 when you're done fiddling.
1860 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001861 if isprivate is not None:
1862 warnings.warn("the isprivate argument is deprecated; "
1863 "examine DocTestFinder.find() lists instead",
1864 DeprecationWarning)
1865
Tim Peters8485b562004-08-04 18:46:34 +00001866 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001867 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001868 # DWA - m will still be None if this wasn't invoked from the command
1869 # line, in which case the following TypeError is about as good an error
1870 # as we should expect
1871 m = sys.modules.get('__main__')
1872
Tim Peters8485b562004-08-04 18:46:34 +00001873 # Check that we were actually given a module.
1874 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001875 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001876
1877 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001878 if name is None:
1879 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001880
1881 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001882 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001883
1884 if raise_on_error:
1885 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1886 else:
1887 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1888
Tim Peters8485b562004-08-04 18:46:34 +00001889 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1890 runner.run(test)
1891
Tim Peters8a7d2d52001-01-16 07:10:57 +00001892 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001893 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001894
Tim Peters8485b562004-08-04 18:46:34 +00001895 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001896
Tim Peters8485b562004-08-04 18:46:34 +00001897def run_docstring_examples(f, globs, verbose=False, name="NoName",
1898 compileflags=None, optionflags=0):
1899 """
1900 Test examples in the given object's docstring (`f`), using `globs`
1901 as globals. Optional argument `name` is used in failure messages.
1902 If the optional argument `verbose` is true, then generate output
1903 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001904
Tim Peters8485b562004-08-04 18:46:34 +00001905 `compileflags` gives the set of flags that should be used by the
1906 Python compiler when running the examples. If not specified, then
1907 it will default to the set of future-import flags that apply to
1908 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001909
Tim Peters8485b562004-08-04 18:46:34 +00001910 Optional keyword arg `optionflags` specifies options for the
1911 testing and output. See the documentation for `testmod` for more
1912 information.
1913 """
1914 # Find, parse, and run all tests in the given module.
1915 finder = DocTestFinder(verbose=verbose, recurse=False)
1916 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1917 for test in finder.find(f, name, globs=globs):
1918 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001919
Tim Peters8485b562004-08-04 18:46:34 +00001920######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001921## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001922######################################################################
1923# This is provided only for backwards compatibility. It's not
1924# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001925
Tim Peters8485b562004-08-04 18:46:34 +00001926class Tester:
1927 def __init__(self, mod=None, globs=None, verbose=None,
1928 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001929
1930 warnings.warn("class Tester is deprecated; "
1931 "use class doctest.DocTestRunner instead",
1932 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001933 if mod is None and globs is None:
1934 raise TypeError("Tester.__init__: must specify mod or globs")
1935 if mod is not None and not _ismodule(mod):
1936 raise TypeError("Tester.__init__: mod must be a module; %r" %
1937 (mod,))
1938 if globs is None:
1939 globs = mod.__dict__
1940 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001941
Tim Peters8485b562004-08-04 18:46:34 +00001942 self.verbose = verbose
1943 self.isprivate = isprivate
1944 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001945 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001946 self.testrunner = DocTestRunner(verbose=verbose,
1947 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001948
Tim Peters8485b562004-08-04 18:46:34 +00001949 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001950 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001951 if self.verbose:
1952 print "Running string", name
1953 (f,t) = self.testrunner.run(test)
1954 if self.verbose:
1955 print f, "of", t, "examples failed in string", name
1956 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001957
Tim Petersf3f57472004-08-08 06:11:48 +00001958 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001959 f = t = 0
1960 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001961 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001962 for test in tests:
1963 (f2, t2) = self.testrunner.run(test)
1964 (f,t) = (f+f2, t+t2)
1965 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001966
Tim Peters8485b562004-08-04 18:46:34 +00001967 def rundict(self, d, name, module=None):
1968 import new
1969 m = new.module(name)
1970 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001971 if module is None:
1972 module = False
1973 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001974
Tim Peters8485b562004-08-04 18:46:34 +00001975 def run__test__(self, d, name):
1976 import new
1977 m = new.module(name)
1978 m.__test__ = d
1979 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001980
Tim Peters8485b562004-08-04 18:46:34 +00001981 def summarize(self, verbose=None):
1982 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001983
Tim Peters8485b562004-08-04 18:46:34 +00001984 def merge(self, other):
1985 d = self.testrunner._name2ft
1986 for name, (f, t) in other.testrunner._name2ft.items():
1987 if name in d:
1988 print "*** Tester.merge: '" + name + "' in both" \
1989 " testers; summing outcomes."
1990 f2, t2 = d[name]
1991 f = f + f2
1992 t = t + t2
1993 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001994
Tim Peters8485b562004-08-04 18:46:34 +00001995######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001996## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001997######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001998
Tim Peters19397e52004-08-06 22:02:59 +00001999class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002000
Edward Loper34fcb142004-08-09 02:45:41 +00002001 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2002 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002003
Jim Fultona643b652004-07-14 19:06:50 +00002004 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002005 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002006 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002007 self._dt_test = test
2008 self._dt_setUp = setUp
2009 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002010
Jim Fultona643b652004-07-14 19:06:50 +00002011 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00002012 if self._dt_setUp is not None:
2013 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00002014
2015 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00002016 if self._dt_tearDown is not None:
2017 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002018
2019 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002020 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002021 old = sys.stdout
2022 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00002023 runner = DocTestRunner(optionflags=self._dt_optionflags,
2024 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002025
Jim Fultona643b652004-07-14 19:06:50 +00002026 try:
Tim Peters19397e52004-08-06 22:02:59 +00002027 runner.DIVIDER = "-"*70
2028 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00002029 finally:
2030 sys.stdout = old
2031
2032 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002033 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002034
Tim Peters19397e52004-08-06 22:02:59 +00002035 def format_failure(self, err):
2036 test = self._dt_test
2037 if test.lineno is None:
2038 lineno = 'unknown line number'
2039 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002040 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002041 lname = '.'.join(test.name.split('.')[-1:])
2042 return ('Failed doctest test for %s\n'
2043 ' File "%s", line %s, in %s\n\n%s'
2044 % (test.name, test.filename, lineno, lname, err)
2045 )
2046
2047 def debug(self):
2048 r"""Run the test case without results and without catching exceptions
2049
2050 The unit test framework includes a debug method on test cases
2051 and test suites to support post-mortem debugging. The test code
2052 is run in such a way that errors are not caught. This way a
2053 caller can catch the errors and initiate post-mortem debugging.
2054
2055 The DocTestCase provides a debug method that raises
2056 UnexpectedException errors if there is an unexepcted
2057 exception:
2058
Edward Lopera1ef6112004-08-09 16:14:41 +00002059 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002060 ... {}, 'foo', 'foo.py', 0)
2061 >>> case = DocTestCase(test)
2062 >>> try:
2063 ... case.debug()
2064 ... except UnexpectedException, failure:
2065 ... pass
2066
2067 The UnexpectedException contains the test, the example, and
2068 the original exception:
2069
2070 >>> failure.test is test
2071 True
2072
2073 >>> failure.example.want
2074 '42\n'
2075
2076 >>> exc_info = failure.exc_info
2077 >>> raise exc_info[0], exc_info[1], exc_info[2]
2078 Traceback (most recent call last):
2079 ...
2080 KeyError
2081
2082 If the output doesn't match, then a DocTestFailure is raised:
2083
Edward Lopera1ef6112004-08-09 16:14:41 +00002084 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002085 ... >>> x = 1
2086 ... >>> x
2087 ... 2
2088 ... ''', {}, 'foo', 'foo.py', 0)
2089 >>> case = DocTestCase(test)
2090
2091 >>> try:
2092 ... case.debug()
2093 ... except DocTestFailure, failure:
2094 ... pass
2095
2096 DocTestFailure objects provide access to the test:
2097
2098 >>> failure.test is test
2099 True
2100
2101 As well as to the example:
2102
2103 >>> failure.example.want
2104 '2\n'
2105
2106 and the actual output:
2107
2108 >>> failure.got
2109 '1\n'
2110
2111 """
2112
Edward Loper34fcb142004-08-09 02:45:41 +00002113 runner = DebugRunner(optionflags=self._dt_optionflags,
2114 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002115 runner.run(self._dt_test)
Jim Fultona643b652004-07-14 19:06:50 +00002116
2117 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002118 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002119
2120 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002121 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002122 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2123
2124 __str__ = __repr__
2125
2126 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002127 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002128
Tim Peters19397e52004-08-06 22:02:59 +00002129def DocTestSuite(module=None, globs=None, extraglobs=None,
2130 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002131 setUp=lambda: None, tearDown=lambda: None,
2132 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002133 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002134 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002135
Tim Peters19397e52004-08-06 22:02:59 +00002136 This converts each documentation string in a module that
2137 contains doctest tests to a unittest test case. If any of the
2138 tests in a doc string fail, then the test case fails. An exception
2139 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002140 (sometimes approximate) line number.
2141
Tim Peters19397e52004-08-06 22:02:59 +00002142 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002143 can be either a module or a module name.
2144
2145 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002146 """
Jim Fultona643b652004-07-14 19:06:50 +00002147
Tim Peters8485b562004-08-04 18:46:34 +00002148 if test_finder is None:
2149 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002150
Tim Peters19397e52004-08-06 22:02:59 +00002151 module = _normalize_module(module)
2152 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2153 if globs is None:
2154 globs = module.__dict__
2155 if not tests: # [XX] why do we want to do this?
2156 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002157
2158 tests.sort()
2159 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002160 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002161 if len(test.examples) == 0:
2162 continue
Tim Peters8485b562004-08-04 18:46:34 +00002163 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002164 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002165 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002166 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002167 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002168 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2169 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002170
2171 return suite
2172
2173class DocFileCase(DocTestCase):
2174
2175 def id(self):
2176 return '_'.join(self._dt_test.name.split('.'))
2177
2178 def __repr__(self):
2179 return self._dt_test.filename
2180 __str__ = __repr__
2181
2182 def format_failure(self, err):
2183 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2184 % (self._dt_test.name, self._dt_test.filename, err)
2185 )
2186
2187def DocFileTest(path, package=None, globs=None,
2188 setUp=None, tearDown=None,
2189 optionflags=0):
2190 package = _normalize_module(package)
2191 name = path.split('/')[-1]
2192 dir = os.path.split(package.__file__)[0]
2193 path = os.path.join(dir, *(path.split('/')))
2194 doc = open(path).read()
2195
2196 if globs is None:
2197 globs = {}
2198
Edward Lopera1ef6112004-08-09 16:14:41 +00002199 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002200
2201 return DocFileCase(test, optionflags, setUp, tearDown)
2202
2203def DocFileSuite(*paths, **kw):
2204 """Creates a suite of doctest files.
2205
2206 One or more text file paths are given as strings. These should
2207 use "/" characters to separate path segments. Paths are relative
2208 to the directory of the calling module, or relative to the package
2209 passed as a keyword argument.
2210
2211 A number of options may be provided as keyword arguments:
2212
2213 package
2214 The name of a Python package. Text-file paths will be
2215 interpreted relative to the directory containing this package.
2216 The package may be supplied as a package object or as a dotted
2217 package name.
2218
2219 setUp
2220 The name of a set-up function. This is called before running the
2221 tests in each file.
2222
2223 tearDown
2224 The name of a tear-down function. This is called after running the
2225 tests in each file.
2226
2227 globs
2228 A dictionary containing initial global variables for the tests.
2229 """
2230 suite = unittest.TestSuite()
2231
2232 # We do this here so that _normalize_module is called at the right
2233 # level. If it were called in DocFileTest, then this function
2234 # would be the caller and we might guess the package incorrectly.
2235 kw['package'] = _normalize_module(kw.get('package'))
2236
2237 for path in paths:
2238 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002239
Tim Petersdb3756d2003-06-29 05:30:48 +00002240 return suite
2241
Tim Peters8485b562004-08-04 18:46:34 +00002242######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002243## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002244######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002245
Tim Peters19397e52004-08-06 22:02:59 +00002246def script_from_examples(s):
2247 r"""Extract script from text with examples.
2248
2249 Converts text with examples to a Python script. Example input is
2250 converted to regular code. Example output and all other words
2251 are converted to comments:
2252
2253 >>> text = '''
2254 ... Here are examples of simple math.
2255 ...
2256 ... Python has super accurate integer addition
2257 ...
2258 ... >>> 2 + 2
2259 ... 5
2260 ...
2261 ... And very friendly error messages:
2262 ...
2263 ... >>> 1/0
2264 ... To Infinity
2265 ... And
2266 ... Beyond
2267 ...
2268 ... You can use logic if you want:
2269 ...
2270 ... >>> if 0:
2271 ... ... blah
2272 ... ... blah
2273 ... ...
2274 ...
2275 ... Ho hum
2276 ... '''
2277
2278 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002279 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002280 #
Edward Lopera5db6002004-08-12 02:41:30 +00002281 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002282 #
2283 2 + 2
2284 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002285 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002286 #
Edward Lopera5db6002004-08-12 02:41:30 +00002287 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002288 #
2289 1/0
2290 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002291 ## To Infinity
2292 ## And
2293 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002294 #
Edward Lopera5db6002004-08-12 02:41:30 +00002295 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002296 #
2297 if 0:
2298 blah
2299 blah
2300 <BLANKLINE>
2301 #
Edward Lopera5db6002004-08-12 02:41:30 +00002302 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002303 """
2304
Edward Lopera1ef6112004-08-09 16:14:41 +00002305 return DocTestParser().get_program(s)
Tim Peters19397e52004-08-06 22:02:59 +00002306
Tim Peters8485b562004-08-04 18:46:34 +00002307def _want_comment(example):
2308 """
Tim Peters19397e52004-08-06 22:02:59 +00002309 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002310 """
Jim Fultona643b652004-07-14 19:06:50 +00002311 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002312 want = example.want
2313 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002314 if want[-1] == '\n':
2315 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002316 want = "\n# ".join(want.split("\n"))
2317 want = "\n# Expected:\n# %s" % want
2318 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002319
2320def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002321 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002322
2323 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002324 test to be debugged and the name (within the module) of the object
2325 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002326 """
Tim Peters8485b562004-08-04 18:46:34 +00002327 module = _normalize_module(module)
2328 tests = DocTestFinder().find(module)
2329 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002330 if not test:
2331 raise ValueError(name, "not found in tests")
2332 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002333 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002334 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002335
Jim Fultona643b652004-07-14 19:06:50 +00002336def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002337 """Debug a single doctest docstring, in argument `src`'"""
2338 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002339 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002340
Jim Fultona643b652004-07-14 19:06:50 +00002341def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002342 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002343 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002344
Tim Petersb6a04d62004-08-23 21:37:56 +00002345 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2346 # docs say, a file so created cannot be opened by name a second time
2347 # on modern Windows boxes, and execfile() needs to open it.
2348 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002349 f = open(srcfilename, 'w')
2350 f.write(src)
2351 f.close()
2352
Tim Petersb6a04d62004-08-23 21:37:56 +00002353 try:
2354 if globs:
2355 globs = globs.copy()
2356 else:
2357 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002358
Tim Petersb6a04d62004-08-23 21:37:56 +00002359 if pm:
2360 try:
2361 execfile(srcfilename, globs, globs)
2362 except:
2363 print sys.exc_info()[1]
2364 pdb.post_mortem(sys.exc_info()[2])
2365 else:
2366 # Note that %r is vital here. '%s' instead can, e.g., cause
2367 # backslashes to get treated as metacharacters on Windows.
2368 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2369
2370 finally:
2371 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002372
Jim Fultona643b652004-07-14 19:06:50 +00002373def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002374 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002375
2376 Provide the module (or dotted name of the module) containing the
2377 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002378 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002379 """
Tim Peters8485b562004-08-04 18:46:34 +00002380 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002381 testsrc = testsource(module, name)
2382 debug_script(testsrc, pm, module.__dict__)
2383
Tim Peters8485b562004-08-04 18:46:34 +00002384######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002385## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002386######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002387class _TestClass:
2388 """
2389 A pointless class, for sanity-checking of docstring testing.
2390
2391 Methods:
2392 square()
2393 get()
2394
2395 >>> _TestClass(13).get() + _TestClass(-12).get()
2396 1
2397 >>> hex(_TestClass(13).square().get())
2398 '0xa9'
2399 """
2400
2401 def __init__(self, val):
2402 """val -> _TestClass object with associated value val.
2403
2404 >>> t = _TestClass(123)
2405 >>> print t.get()
2406 123
2407 """
2408
2409 self.val = val
2410
2411 def square(self):
2412 """square() -> square TestClass's associated value
2413
2414 >>> _TestClass(13).square().get()
2415 169
2416 """
2417
2418 self.val = self.val ** 2
2419 return self
2420
2421 def get(self):
2422 """get() -> return TestClass's associated value.
2423
2424 >>> x = _TestClass(-42)
2425 >>> print x.get()
2426 -42
2427 """
2428
2429 return self.val
2430
2431__test__ = {"_TestClass": _TestClass,
2432 "string": r"""
2433 Example of a string object, searched as-is.
2434 >>> x = 1; y = 2
2435 >>> x + y, x * y
2436 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002437 """,
2438 "bool-int equivalence": r"""
2439 In 2.2, boolean expressions displayed
2440 0 or 1. By default, we still accept
2441 them. This can be disabled by passing
2442 DONT_ACCEPT_TRUE_FOR_1 to the new
2443 optionflags argument.
2444 >>> 4 == 4
2445 1
2446 >>> 4 == 4
2447 True
2448 >>> 4 > 4
2449 0
2450 >>> 4 > 4
2451 False
2452 """,
Tim Peters8485b562004-08-04 18:46:34 +00002453 "blank lines": r"""
2454 Blank lines can be marked with <BLANKLINE>:
2455 >>> print 'foo\n\nbar\n'
2456 foo
2457 <BLANKLINE>
2458 bar
2459 <BLANKLINE>
2460 """,
2461 }
2462# "ellipsis": r"""
2463# If the ellipsis flag is used, then '...' can be used to
2464# elide substrings in the desired output:
2465# >>> print range(1000)
2466# [0, 1, 2, ..., 999]
2467# """,
2468# "whitespace normalization": r"""
2469# If the whitespace normalization flag is used, then
2470# differences in whitespace are ignored.
2471# >>> print range(30)
2472# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2473# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2474# 27, 28, 29]
2475# """,
2476# }
2477
2478def test1(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002479>>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2480... "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002481>>> from doctest import Tester
2482>>> t = Tester(globs={'x': 42}, verbose=0)
2483>>> t.runstring(r'''
2484... >>> x = x * 2
2485... >>> print x
2486... 42
2487... ''', 'XYZ')
2488**********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00002489Line 3, in XYZ
2490Failed example:
2491 print x
2492Expected:
2493 42
2494Got:
2495 84
Tim Peters8485b562004-08-04 18:46:34 +00002496(1, 2)
2497>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2498(0, 2)
2499>>> t.summarize()
2500**********************************************************************
25011 items had failures:
2502 1 of 2 in XYZ
2503***Test Failed*** 1 failures.
2504(1, 4)
2505>>> t.summarize(verbose=1)
25061 items passed all tests:
2507 2 tests in example2
2508**********************************************************************
25091 items had failures:
2510 1 of 2 in XYZ
25114 tests in 2 items.
25123 passed and 1 failed.
2513***Test Failed*** 1 failures.
2514(1, 4)
2515"""
2516
2517def test2(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002518 >>> warnings.filterwarnings("ignore", "class Tester",
2519 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002520 >>> t = Tester(globs={}, verbose=1)
2521 >>> test = r'''
2522 ... # just an example
2523 ... >>> x = 1 + 2
2524 ... >>> x
2525 ... 3
2526 ... '''
2527 >>> t.runstring(test, "Example")
2528 Running string Example
2529 Trying: x = 1 + 2
2530 Expecting: nothing
2531 ok
2532 Trying: x
2533 Expecting: 3
2534 ok
2535 0 of 2 examples failed in string Example
2536 (0, 2)
2537"""
2538def test3(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002539 >>> warnings.filterwarnings("ignore", "class Tester",
2540 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002541 >>> t = Tester(globs={}, verbose=0)
2542 >>> def _f():
2543 ... '''Trivial docstring example.
2544 ... >>> assert 2 == 2
2545 ... '''
2546 ... return 32
2547 ...
2548 >>> t.rundoc(_f) # expect 0 failures in 1 example
2549 (0, 1)
2550"""
2551def test4(): """
2552 >>> import new
2553 >>> m1 = new.module('_m1')
2554 >>> m2 = new.module('_m2')
2555 >>> test_data = \"""
2556 ... def _f():
2557 ... '''>>> assert 1 == 1
2558 ... '''
2559 ... def g():
2560 ... '''>>> assert 2 != 1
2561 ... '''
2562 ... class H:
2563 ... '''>>> assert 2 > 1
2564 ... '''
2565 ... def bar(self):
2566 ... '''>>> assert 1 < 2
2567 ... '''
2568 ... \"""
2569 >>> exec test_data in m1.__dict__
2570 >>> exec test_data in m2.__dict__
2571 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2572
2573 Tests that objects outside m1 are excluded:
2574
Tim Peters3ddd60a2004-08-08 02:43:33 +00002575 >>> warnings.filterwarnings("ignore", "class Tester",
2576 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002577 >>> t = Tester(globs={}, verbose=0)
Tim Petersf727c6c2004-08-08 01:48:59 +00002578 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Tim Peters8485b562004-08-04 18:46:34 +00002579 (0, 4)
2580
Tim Petersf727c6c2004-08-08 01:48:59 +00002581 Once more, not excluding stuff outside m1:
Tim Peters8485b562004-08-04 18:46:34 +00002582
2583 >>> t = Tester(globs={}, verbose=0)
2584 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2585 (0, 8)
2586
2587 The exclusion of objects from outside the designated module is
2588 meant to be invoked automagically by testmod.
2589
Tim Petersf727c6c2004-08-08 01:48:59 +00002590 >>> testmod(m1, verbose=False)
2591 (0, 4)
Tim Peters8485b562004-08-04 18:46:34 +00002592"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002593
2594def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002595 #import doctest
2596 #doctest.testmod(doctest, verbose=False,
2597 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2598 # UNIFIED_DIFF)
2599 #print '~'*70
2600 r = unittest.TextTestRunner()
2601 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002602
2603if __name__ == "__main__":
2604 _test()