blob: c7a183b67fefa87ea4d00836ea9e48cda884a386 [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8485b562004-08-04 18:46:34 +00002# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
Tim Peters19397e52004-08-06 22:02:59 +00003# Major enhancements and refactoring by:
Tim Peters8485b562004-08-04 18:46:34 +00004# Jim Fulton
5# Edward Loper
Tim Peters8a7d2d52001-01-16 07:10:57 +00006
7# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
8
Martin v. Löwis92816de2004-05-31 19:01:00 +00009r"""Module doctest -- a framework for running examples in docstrings.
Tim Peters8a7d2d52001-01-16 07:10:57 +000010
11NORMAL USAGE
12
Tim Peters80e53142004-08-09 04:34:45 +000013In simplest use, end each module M to be tested with:
Tim Peters8a7d2d52001-01-16 07:10:57 +000014
15def _test():
Tim Peters80e53142004-08-09 04:34:45 +000016 import doctest
17 return doctest.testmod()
Tim Peters8a7d2d52001-01-16 07:10:57 +000018
19if __name__ == "__main__":
20 _test()
21
22Then running the module as a script will cause the examples in the
23docstrings to get executed and verified:
24
25python M.py
26
27This won't display anything unless an example fails, in which case the
28failing example(s) and the cause(s) of the failure(s) are printed to stdout
29(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
30line of output is "Test failed.".
31
32Run it with the -v switch instead:
33
34python M.py -v
35
36and a detailed report of all examples tried is printed to stdout, along
37with assorted summaries at the end.
38
Tim Peters80e53142004-08-09 04:34:45 +000039You can force verbose mode by passing "verbose=True" to testmod, or prohibit
40it by passing "verbose=False". In either of those cases, sys.argv is not
Tim Peters8a7d2d52001-01-16 07:10:57 +000041examined by testmod.
42
43In any case, testmod returns a 2-tuple of ints (f, t), where f is the
44number of docstring examples that failed and t is the total number of
45docstring examples attempted.
46
Tim Peters80e53142004-08-09 04:34:45 +000047There are a variety of other ways to run doctests, including integration
48with the unittest framework, and support for running non-Python text
49files containing doctests. There are also many ways to override parts
50of doctest's default behaviors. See the Library Reference Manual for
51details.
52
Tim Peters8a7d2d52001-01-16 07:10:57 +000053
54WHICH DOCSTRINGS ARE EXAMINED?
55
56+ M.__doc__.
57
58+ f.__doc__ for all functions f in M.__dict__.values(), except those
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000059 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000060
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000061+ C.__doc__ for all classes C in M.__dict__.values(), except those
62 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000063
64+ If M.__test__ exists and "is true", it must be a dict, and
65 each entry maps a (string) name to a function object, class object, or
66 string. Function and class object docstrings found from M.__test__
Tim Peters80e53142004-08-09 04:34:45 +000067 are searched, and strings are searched directly as if they were docstrings.
68 In output, a key K in M.__test__ appears with name
Tim Peters8a7d2d52001-01-16 07:10:57 +000069 <name of M>.__test__.K
70
71Any classes found are recursively searched similarly, to test docstrings in
Tim Peters80e53142004-08-09 04:34:45 +000072their contained methods and nested classes.
Tim Peters8a7d2d52001-01-16 07:10:57 +000073
Tim Peters8a7d2d52001-01-16 07:10:57 +000074
Tim Peters8a7d2d52001-01-16 07:10:57 +000075WHAT'S THE EXECUTION CONTEXT?
76
77By default, each time testmod finds a docstring to test, it uses a *copy*
78of M's globals (so that running tests on a module doesn't change the
79module's real globals, and so that one test in M can't leave behind crumbs
80that accidentally allow another test to work). This means examples can
81freely use any names defined at top-level in M. It also means that sloppy
82imports (see above) can cause examples in external docstrings to use
83globals inappropriate for them.
84
85You can force use of your own dict as the execution context by passing
86"globs=your_dict" to testmod instead. Presumably this would be a copy of
87M.__dict__ merged with the globals from other imported modules.
88
89
Tim Peters8a7d2d52001-01-16 07:10:57 +000090WHAT ABOUT EXCEPTIONS?
91
92No problem, as long as the only output generated by the example is the
93traceback itself. For example:
94
Tim Peters60e23f42001-02-14 00:43:21 +000095 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +000096 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +000097 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +000098 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +000099 >>>
100
Tim Peters80e53142004-08-09 04:34:45 +0000101Note that only the exception type and value are compared.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000102
103
Tim Peters80e53142004-08-09 04:34:45 +0000104SO WHAT DOES A DOCTEST EXAMPLE LOOK LIKE ALREADY!?
Tim Peters8a7d2d52001-01-16 07:10:57 +0000105
106Oh ya. It's easy! In most cases a copy-and-paste of an interactive
107console session works fine -- just make sure the leading whitespace is
108rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
109right, but doctest is not in the business of guessing what you think a tab
110means).
111
112 >>> # comments are ignored
113 >>> x = 12
114 >>> x
115 12
116 >>> if x == 13:
117 ... print "yes"
118 ... else:
119 ... print "no"
120 ... print "NO"
121 ... print "NO!!!"
122 ...
123 no
124 NO
125 NO!!!
126 >>>
127
128Any expected output must immediately follow the final ">>>" or "..." line
129containing the code, and the expected output (if any) extends to the next
130">>>" or all-whitespace line. That's it.
131
132Bummers:
133
Tim Peters8a7d2d52001-01-16 07:10:57 +0000134+ Output to stdout is captured, but not output to stderr (exception
135 tracebacks are captured via a different means).
136
Martin v. Löwis92816de2004-05-31 19:01:00 +0000137+ If you continue a line via backslashing in an interactive session,
138 or for any other reason use a backslash, you should use a raw
139 docstring, which will preserve your backslahses exactly as you type
140 them:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000141
Tim Peters4e0e1b62004-07-07 20:54:48 +0000142 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000143 ... r'''Backslashes in a raw docstring: m\n'''
144 >>> print f.__doc__
145 Backslashes in a raw docstring: m\n
Tim Peters8a7d2d52001-01-16 07:10:57 +0000146
Martin v. Löwis92816de2004-05-31 19:01:00 +0000147 Otherwise, the backslash will be interpreted as part of the string.
148 E.g., the "\n" above would be interpreted as a newline character.
149 Alternatively, you can double each backslash in the doctest version
150 (and not use a raw string):
151
Tim Peters4e0e1b62004-07-07 20:54:48 +0000152 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000153 ... '''Backslashes in a raw docstring: m\\n'''
154 >>> print f.__doc__
155 Backslashes in a raw docstring: m\n
Tim Peters4e0e1b62004-07-07 20:54:48 +0000156
Tim Peters8a7d2d52001-01-16 07:10:57 +0000157The starting column doesn't matter:
158
159>>> assert "Easy!"
160 >>> import math
161 >>> math.floor(1.9)
162 1.0
163
164and as many leading whitespace characters are stripped from the expected
165output as appeared in the initial ">>>" line that triggered it.
166
167If you execute this very file, the examples above will be found and
Tim Peters80e53142004-08-09 04:34:45 +0000168executed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000169"""
Edward Loper8e4a34b2004-08-12 02:34:27 +0000170__docformat__ = 'reStructuredText en'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000171
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000172__all__ = [
Tim Peters8485b562004-08-04 18:46:34 +0000173 'is_private',
174 'Example',
175 'DocTest',
176 'DocTestFinder',
177 'DocTestRunner',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000178 'testmod',
179 'run_docstring_examples',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000180 'Tester',
Tim Peters19397e52004-08-06 22:02:59 +0000181 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000182 'DocTestSuite',
183 'testsource',
184 'debug',
Tim Peters8485b562004-08-04 18:46:34 +0000185# 'master',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000186]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000187
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000188import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000189
Tim Peters19397e52004-08-06 22:02:59 +0000190import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000191import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000192import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000193from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000194
Jim Fulton356fd192004-08-09 11:34:47 +0000195real_pdb_set_trace = pdb.set_trace
196
Tim Peters19397e52004-08-06 22:02:59 +0000197# There are 4 basic classes:
198# - Example: a <source, want> pair, plus an intra-docstring line number.
199# - DocTest: a collection of examples, parsed from a docstring, plus
200# info about where the docstring came from (name, filename, lineno).
201# - DocTestFinder: extracts DocTests from a given object's docstring and
202# its contained objects' docstrings.
203# - DocTestRunner: runs DocTest cases, and accumulates statistics.
204#
205# So the basic picture is:
206#
207# list of:
208# +------+ +---------+ +-------+
209# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
210# +------+ +---------+ +-------+
211# | Example |
212# | ... |
213# | Example |
214# +---------+
215
Edward Loperac20f572004-08-12 02:02:24 +0000216# Option constants.
217OPTIONFLAGS_BY_NAME = {}
218def register_optionflag(name):
219 flag = 1 << len(OPTIONFLAGS_BY_NAME)
220 OPTIONFLAGS_BY_NAME[name] = flag
221 return flag
222
223DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
224DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
225NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
226ELLIPSIS = register_optionflag('ELLIPSIS')
227UNIFIED_DIFF = register_optionflag('UNIFIED_DIFF')
228CONTEXT_DIFF = register_optionflag('CONTEXT_DIFF')
229
230# Special string markers for use in `want` strings:
231BLANKLINE_MARKER = '<BLANKLINE>'
232ELLIPSIS_MARKER = '...'
233
Tim Peters8485b562004-08-04 18:46:34 +0000234######################################################################
235## Table of Contents
236######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000237# 1. Utility Functions
238# 2. Example & DocTest -- store test cases
239# 3. DocTest Parser -- extracts examples from strings
240# 4. DocTest Finder -- extracts test cases from objects
241# 5. DocTest Runner -- runs test cases
242# 6. Test Functions -- convenient wrappers for testing
243# 7. Tester Class -- for backwards compatibility
244# 8. Unittest Support
245# 9. Debugging Support
246# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000247
Tim Peters8485b562004-08-04 18:46:34 +0000248######################################################################
249## 1. Utility Functions
250######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000251
252def is_private(prefix, base):
253 """prefix, base -> true iff name prefix + "." + base is "private".
254
255 Prefix may be an empty string, and base does not contain a period.
256 Prefix is ignored (although functions you write conforming to this
257 protocol may make use of it).
258 Return true iff base begins with an (at least one) underscore, but
259 does not both begin and end with (at least) two underscores.
260
Tim Petersbafb1fe2004-08-08 01:52:57 +0000261 >>> warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
262 ... "doctest", 0)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000263 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000264 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000265 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000266 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000267 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000268 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000269 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000270 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000271 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000272 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000273 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000274 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000275 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000276 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000277 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000278 warnings.warn("is_private is deprecated; it wasn't useful; "
279 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000280 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000281 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
282
Tim Peters8485b562004-08-04 18:46:34 +0000283def _extract_future_flags(globs):
284 """
285 Return the compiler-flags associated with the future features that
286 have been imported into the given namespace (globs).
287 """
288 flags = 0
289 for fname in __future__.all_feature_names:
290 feature = globs.get(fname, None)
291 if feature is getattr(__future__, fname):
292 flags |= feature.compiler_flag
293 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000294
Tim Peters8485b562004-08-04 18:46:34 +0000295def _normalize_module(module, depth=2):
296 """
297 Return the module specified by `module`. In particular:
298 - If `module` is a module, then return module.
299 - If `module` is a string, then import and return the
300 module with that name.
301 - If `module` is None, then return the calling module.
302 The calling module is assumed to be the module of
303 the stack frame at the given depth in the call stack.
304 """
305 if inspect.ismodule(module):
306 return module
307 elif isinstance(module, (str, unicode)):
308 return __import__(module, globals(), locals(), ["*"])
309 elif module is None:
310 return sys.modules[sys._getframe(depth).f_globals['__name__']]
311 else:
312 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000313
Edward Lopera1ef6112004-08-09 16:14:41 +0000314def _tag_msg(tag, msg, indent=' '):
Tim Peters8485b562004-08-04 18:46:34 +0000315 """
316 Return a string that displays a tag-and-message pair nicely,
317 keeping the tag and its message on the same line when that
Edward Lopera1ef6112004-08-09 16:14:41 +0000318 makes sense. If the message is displayed on separate lines,
319 then `indent` is added to the beginning of each line.
Tim Peters8485b562004-08-04 18:46:34 +0000320 """
Tim Peters8485b562004-08-04 18:46:34 +0000321 # If the message doesn't end in a newline, then add one.
322 if msg[-1:] != '\n':
323 msg += '\n'
324 # If the message is short enough, and contains no internal
325 # newlines, then display it on the same line as the tag.
326 # Otherwise, display the tag on its own line.
327 if (len(tag) + len(msg) < 75 and
328 msg.find('\n', 0, len(msg)-1) == -1):
329 return '%s: %s' % (tag, msg)
330 else:
Edward Lopera1ef6112004-08-09 16:14:41 +0000331 msg = '\n'.join([indent+l for l in msg[:-1].split('\n')])
332 return '%s:\n%s\n' % (tag, msg)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000333
Edward Loper8e4a34b2004-08-12 02:34:27 +0000334def _exception_traceback(exc_info):
335 """
336 Return a string containing a traceback message for the given
337 exc_info tuple (as returned by sys.exc_info()).
338 """
339 # Get a traceback message.
340 excout = StringIO()
341 exc_type, exc_val, exc_tb = exc_info
342 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
343 return excout.getvalue()
344
Tim Peters8485b562004-08-04 18:46:34 +0000345# Override some StringIO methods.
346class _SpoofOut(StringIO):
347 def getvalue(self):
348 result = StringIO.getvalue(self)
349 # If anything at all was written, make sure there's a trailing
350 # newline. There's no way for the expected output to indicate
351 # that a trailing newline is missing.
352 if result and not result.endswith("\n"):
353 result += "\n"
354 # Prevent softspace from screwing up the next test case, in
355 # case they used print with a trailing comma in an example.
356 if hasattr(self, "softspace"):
357 del self.softspace
358 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000359
Tim Peters8485b562004-08-04 18:46:34 +0000360 def truncate(self, size=None):
361 StringIO.truncate(self, size)
362 if hasattr(self, "softspace"):
363 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000364
Tim Peters26b3ebb2004-08-19 08:10:08 +0000365# Worst-case linear-time ellipsis matching.
366def ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000367 """
368 Essentially the only subtle case:
369 >>> ellipsis_match('aa...aa', 'aaa')
370 False
371 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000372 if ELLIPSIS_MARKER not in want:
373 return want == got
374 # Remove \n from ...\n, else the newline will be required,
375 # and (for example) ... on a line by itself can't match
376 # nothing gracefully.
377 want = want.replace(ELLIPSIS_MARKER + '\n', ELLIPSIS_MARKER)
Tim Petersdc5de3b2004-08-19 14:06:20 +0000378
Tim Peters26b3ebb2004-08-19 08:10:08 +0000379 # Find "the real" strings.
380 ws = want.split(ELLIPSIS_MARKER)
381 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000382
Tim Petersdc5de3b2004-08-19 14:06:20 +0000383 # Deal with exact matches possibly needed at one or both ends.
384 startpos, endpos = 0, len(got)
385 w = ws[0]
386 if w: # starts with exact match
387 if got.startswith(w):
388 startpos = len(w)
389 del ws[0]
390 else:
391 return False
392 w = ws[-1]
393 if w: # ends with exact match
394 if got.endswith(w):
395 endpos -= len(w)
396 del ws[-1]
397 else:
398 return False
399
400 if startpos > endpos:
401 # Exact end matches required more characters than we have, as in
402 # ellipsis_match('aa...aa', 'aaa')
403 return False
404
405 # For the rest, we only need to find the leftmost non-overlapping
406 # match for each piece. If there's no overall match that way alone,
407 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000408 for w in ws:
409 # w may be '' at times, if there are consecutive ellipses, or
410 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000411 # Search for an empty string succeeds, and doesn't change startpos.
412 startpos = got.find(w, startpos, endpos)
413 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000414 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000415 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000416
Tim Petersdc5de3b2004-08-19 14:06:20 +0000417 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000418
Tim Peters8485b562004-08-04 18:46:34 +0000419######################################################################
420## 2. Example & DocTest
421######################################################################
422## - An "example" is a <source, want> pair, where "source" is a
423## fragment of source code, and "want" is the expected output for
424## "source." The Example class also includes information about
425## where the example was extracted from.
426##
Edward Lopera1ef6112004-08-09 16:14:41 +0000427## - A "doctest" is a collection of examples, typically extracted from
428## a string (such as an object's docstring). The DocTest class also
429## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000430
Tim Peters8485b562004-08-04 18:46:34 +0000431class Example:
432 """
433 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000434 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000435
Edward Loper74bca7a2004-08-12 02:27:44 +0000436 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000437 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000438
Edward Loper74bca7a2004-08-12 02:27:44 +0000439 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000440 from stdout, or a traceback in case of exception). `want` ends
441 with a newline unless it's empty, in which case it's an empty
442 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000443
Edward Loper74bca7a2004-08-12 02:27:44 +0000444 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000445 this Example where the Example begins. This line number is
446 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000447
448 - indent: The example's indentation in the DocTest string.
449 I.e., the number of space characters that preceed the
450 example's first prompt.
451
452 - options: A dictionary mapping from option flags to True or
453 False, which is used to override default options for this
454 example. Any option flags not contained in this dictionary
455 are left at their default value (as specified by the
456 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000457 """
Edward Loper74bca7a2004-08-12 02:27:44 +0000458 def __init__(self, source, want, lineno, indent=0, options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000459 # Normalize inputs.
460 if not source.endswith('\n'):
461 source += '\n'
462 if want and not want.endswith('\n'):
463 want += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000464 # Store properties.
465 self.source = source
466 self.want = want
467 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000468 self.indent = indent
469 if options is None: options = {}
470 self.options = options
Tim Peters8a7d2d52001-01-16 07:10:57 +0000471
Tim Peters8485b562004-08-04 18:46:34 +0000472class DocTest:
473 """
474 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000475 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000476
Tim Peters8485b562004-08-04 18:46:34 +0000477 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000478
Tim Peters8485b562004-08-04 18:46:34 +0000479 - globs: The namespace (aka globals) that the examples should
480 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000481
Tim Peters8485b562004-08-04 18:46:34 +0000482 - name: A name identifying the DocTest (typically, the name of
483 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000484
Tim Peters8485b562004-08-04 18:46:34 +0000485 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000486 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000487
Tim Peters8485b562004-08-04 18:46:34 +0000488 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000489 begins, or `None` if the line number is unavailable. This
490 line number is zero-based, with respect to the beginning of
491 the file.
492
493 - docstring: The string that the examples were extracted from,
494 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000495 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000496 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000497 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000498 Create a new DocTest containing the given examples. The
499 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000500 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000501 assert not isinstance(examples, basestring), \
502 "DocTest no longer accepts str; use DocTestParser instead"
503 self.examples = examples
504 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000505 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000506 self.name = name
507 self.filename = filename
508 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000509
510 def __repr__(self):
511 if len(self.examples) == 0:
512 examples = 'no examples'
513 elif len(self.examples) == 1:
514 examples = '1 example'
515 else:
516 examples = '%d examples' % len(self.examples)
517 return ('<DocTest %s from %s:%s (%s)>' %
518 (self.name, self.filename, self.lineno, examples))
519
520
521 # This lets us sort tests by name:
522 def __cmp__(self, other):
523 if not isinstance(other, DocTest):
524 return -1
525 return cmp((self.name, self.filename, self.lineno, id(self)),
526 (other.name, other.filename, other.lineno, id(other)))
527
528######################################################################
Edward Lopera1ef6112004-08-09 16:14:41 +0000529## 2. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000530######################################################################
531
Edward Lopera1ef6112004-08-09 16:14:41 +0000532class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000533 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000534 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000535 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000536 # This regular expression is used to find doctest examples in a
537 # string. It defines three groups: `source` is the source code
538 # (including leading indentation and prompts); `indent` is the
539 # indentation of the first (PS1) line of the source code; and
540 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000541 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000542 # Source consists of a PS1 line followed by zero or more PS2 lines.
543 (?P<source>
544 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
545 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
546 \n?
547 # Want consists of any non-blank lines that do not start with PS1.
548 (?P<want> (?:(?![ ]*$) # Not a blank line
549 (?![ ]*>>>) # Not a line starting with PS1
550 .*$\n? # But any other line
551 )*)
552 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000553
Tim Peters7ea48dd2004-08-13 01:52:59 +0000554 # A callable returning a true value iff its argument is a blank line
555 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000556 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000557
Edward Lopera1ef6112004-08-09 16:14:41 +0000558 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000559 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000560 Extract all doctest examples from the given string, and
561 collect them into a `DocTest` object.
562
563 `globs`, `name`, `filename`, and `lineno` are attributes for
564 the new `DocTest` object. See the documentation for `DocTest`
565 for more information.
566 """
567 return DocTest(self.get_examples(string, name), globs,
568 name, filename, lineno, string)
569
570 def get_examples(self, string, name='<string>'):
571 """
572 Extract all doctest examples from the given string, and return
573 them as a list of `Example` objects. Line numbers are
574 0-based, because it's most common in doctests that nothing
575 interesting appears on the same line as opening triple-quote,
576 and so the first interesting line is called \"line 1\" then.
577
578 The optional argument `name` is a name identifying this
579 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000580
581 >>> text = '''
582 ... >>> x, y = 2, 3 # no output expected
583 ... >>> if 1:
584 ... ... print x
585 ... ... print y
586 ... 2
587 ... 3
588 ...
589 ... Some text.
590 ... >>> x+y
591 ... 5
592 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000593 >>> for x in DocTestParser().get_examples(text):
Edward Loper78b58f32004-08-09 02:56:02 +0000594 ... print (x.source, x.want, x.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000595 ('x, y = 2, 3 # no output expected\\n', '', 1)
Edward Loper7c748462004-08-09 02:06:06 +0000596 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
Tim Petersbb431472004-08-09 03:51:46 +0000597 ('x+y\\n', '5\\n', 9)
Edward Loper7c748462004-08-09 02:06:06 +0000598 """
599 examples = []
600 charno, lineno = 0, 0
601 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000602 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000603 # Update lineno (lines before this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000604 lineno += string.count('\n', charno, m.start())
Edward Loper7c748462004-08-09 02:06:06 +0000605 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000606 (source, want) = self._parse_example(m, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000607 # Extract extra options from the source.
608 options = self._find_options(source, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000609 # Create an Example, and add it to the list.
Edward Loperb51b2342004-08-17 16:37:12 +0000610 if not self._IS_BLANK_OR_COMMENT(source):
611 examples.append( Example(source, want, lineno,
612 len(m.group('indent')), options) )
Edward Loper7c748462004-08-09 02:06:06 +0000613 # Update lineno (lines inside this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000614 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000615 # Update charno.
616 charno = m.end()
617 return examples
618
Edward Lopera1ef6112004-08-09 16:14:41 +0000619 def get_program(self, string, name="<string>"):
Edward Loper7c748462004-08-09 02:06:06 +0000620 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000621 Return an executable program from the given string, as a string.
Edward Loper7c748462004-08-09 02:06:06 +0000622
623 The format of this isn't rigidly defined. In general, doctest
624 examples become the executable statements in the result, and
625 their expected outputs become comments, preceded by an \"#Expected:\"
626 comment. Everything else (text, comments, everything not part of
627 a doctest test) is also placed in comments.
628
Edward Lopera1ef6112004-08-09 16:14:41 +0000629 The optional argument `name` is a name identifying this
630 string, and is only used for error messages.
631
Edward Loper7c748462004-08-09 02:06:06 +0000632 >>> text = '''
633 ... >>> x, y = 2, 3 # no output expected
634 ... >>> if 1:
635 ... ... print x
636 ... ... print y
637 ... 2
638 ... 3
639 ...
640 ... Some text.
641 ... >>> x+y
642 ... 5
643 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000644 >>> print DocTestParser().get_program(text)
Edward Loper7c748462004-08-09 02:06:06 +0000645 x, y = 2, 3 # no output expected
646 if 1:
647 print x
648 print y
649 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000650 ## 2
651 ## 3
Edward Loper7c748462004-08-09 02:06:06 +0000652 #
Edward Lopera5db6002004-08-12 02:41:30 +0000653 # Some text.
Edward Loper7c748462004-08-09 02:06:06 +0000654 x+y
655 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000656 ## 5
Edward Loper7c748462004-08-09 02:06:06 +0000657 """
Edward Lopera5db6002004-08-12 02:41:30 +0000658 string = string.expandtabs()
659 # If all lines begin with the same indentation, then strip it.
660 min_indent = self._min_indent(string)
661 if min_indent > 0:
662 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
663
Edward Loper7c748462004-08-09 02:06:06 +0000664 output = []
665 charnum, lineno = 0, 0
666 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000667 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000668 # Add any text before this example, as a comment.
669 if m.start() > charnum:
Edward Lopera1ef6112004-08-09 16:14:41 +0000670 lines = string[charnum:m.start()-1].split('\n')
Edward Loper7c748462004-08-09 02:06:06 +0000671 output.extend([self._comment_line(l) for l in lines])
672 lineno += len(lines)
673
674 # Extract source/want from the regexp match.
Edward Loper74bca7a2004-08-12 02:27:44 +0000675 (source, want) = self._parse_example(m, name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000676 # Display the source
677 output.append(source)
678 # Display the expected output, if any
679 if want:
680 output.append('# Expected:')
Edward Lopera5db6002004-08-12 02:41:30 +0000681 output.extend(['## '+l for l in want.split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000682
683 # Update the line number & char number.
Edward Lopera1ef6112004-08-09 16:14:41 +0000684 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000685 charnum = m.end()
686 # Add any remaining text, as comments.
687 output.extend([self._comment_line(l)
Edward Lopera1ef6112004-08-09 16:14:41 +0000688 for l in string[charnum:].split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000689 # Trim junk on both ends.
690 while output and output[-1] == '#':
691 output.pop()
692 while output and output[0] == '#':
693 output.pop(0)
694 # Combine the output, and return it.
695 return '\n'.join(output)
696
Edward Loper74bca7a2004-08-12 02:27:44 +0000697 def _parse_example(self, m, name, lineno):
698 """
699 Given a regular expression match from `_EXAMPLE_RE` (`m`),
700 return a pair `(source, want)`, where `source` is the matched
701 example's source code (with prompts and indentation stripped);
702 and `want` is the example's expected output (with indentation
703 stripped).
704
705 `name` is the string's name, and `lineno` is the line number
706 where the example starts; both are used for error messages.
707 """
Edward Loper7c748462004-08-09 02:06:06 +0000708 # Get the example's indentation level.
709 indent = len(m.group('indent'))
710
711 # Divide source into lines; check that they're properly
712 # indented; and then strip their indentation & prompts.
713 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000714 self._check_prompt_blank(source_lines, indent, name, lineno)
715 self._check_prefix(source_lines[1:], ' '*indent+'.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000716 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000717
718 # Divide want into lines; check that it's properly
719 # indented; and then strip the indentation.
720 want_lines = m.group('want').rstrip().split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000721 self._check_prefix(want_lines, ' '*indent, name,
Edward Loper7c748462004-08-09 02:06:06 +0000722 lineno+len(source_lines))
723 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000724
725 return source, want
726
Edward Loper74bca7a2004-08-12 02:27:44 +0000727 # This regular expression looks for option directives in the
728 # source code of an example. Option directives are comments
729 # starting with "doctest:". Warning: this may give false
730 # positives for string-literals that contain the string
731 # "#doctest:". Eliminating these false positives would require
732 # actually parsing the string; but we limit them by ignoring any
733 # line containing "#doctest:" that is *followed* by a quote mark.
734 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
735 re.MULTILINE)
736
737 def _find_options(self, source, name, lineno):
738 """
739 Return a dictionary containing option overrides extracted from
740 option directives in the given source string.
741
742 `name` is the string's name, and `lineno` is the line number
743 where the example starts; both are used for error messages.
744 """
745 options = {}
746 # (note: with the current regexp, this will match at most once:)
747 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
748 option_strings = m.group(1).replace(',', ' ').split()
749 for option in option_strings:
750 if (option[0] not in '+-' or
751 option[1:] not in OPTIONFLAGS_BY_NAME):
752 raise ValueError('line %r of the doctest for %s '
753 'has an invalid option: %r' %
754 (lineno+1, name, option))
755 flag = OPTIONFLAGS_BY_NAME[option[1:]]
756 options[flag] = (option[0] == '+')
757 if options and self._IS_BLANK_OR_COMMENT(source):
758 raise ValueError('line %r of the doctest for %s has an option '
759 'directive on a line with no example: %r' %
760 (lineno, name, source))
761 return options
762
Edward Lopera5db6002004-08-12 02:41:30 +0000763 # This regular expression finds the indentation of every non-blank
764 # line in a string.
765 _INDENT_RE = re.compile('^([ ]+)(?=\S)', re.MULTILINE)
766
767 def _min_indent(self, s):
768 "Return the minimum indentation of any non-blank line in `s`"
769 return min([len(indent) for indent in self._INDENT_RE.findall(s)])
770
Edward Loper7c748462004-08-09 02:06:06 +0000771 def _comment_line(self, line):
Edward Loper74bca7a2004-08-12 02:27:44 +0000772 "Return a commented form of the given line"
Edward Loper7c748462004-08-09 02:06:06 +0000773 line = line.rstrip()
Tim Petersdd0e4752004-08-09 03:31:56 +0000774 if line:
Edward Lopera5db6002004-08-12 02:41:30 +0000775 return '# '+line
Tim Petersdd0e4752004-08-09 03:31:56 +0000776 else:
777 return '#'
Edward Loper7c748462004-08-09 02:06:06 +0000778
Edward Lopera1ef6112004-08-09 16:14:41 +0000779 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000780 """
781 Given the lines of a source string (including prompts and
782 leading indentation), check to make sure that every prompt is
783 followed by a space character. If any line is not followed by
784 a space character, then raise ValueError.
785 """
Edward Loper7c748462004-08-09 02:06:06 +0000786 for i, line in enumerate(lines):
787 if len(line) >= indent+4 and line[indent+3] != ' ':
788 raise ValueError('line %r of the docstring for %s '
789 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000790 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000791 line[indent:indent+3], line))
792
Edward Lopera1ef6112004-08-09 16:14:41 +0000793 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000794 """
795 Check that every line in the given list starts with the given
796 prefix; if any line does not, then raise a ValueError.
797 """
Edward Loper7c748462004-08-09 02:06:06 +0000798 for i, line in enumerate(lines):
799 if line and not line.startswith(prefix):
800 raise ValueError('line %r of the docstring for %s has '
801 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000802 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000803
804
805######################################################################
806## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000807######################################################################
808
809class DocTestFinder:
810 """
811 A class used to extract the DocTests that are relevant to a given
812 object, from its docstring and the docstrings of its contained
813 objects. Doctests can currently be extracted from the following
814 object types: modules, functions, classes, methods, staticmethods,
815 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000816 """
817
Edward Lopera1ef6112004-08-09 16:14:41 +0000818 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000819 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000820 """
821 Create a new doctest finder.
822
Edward Lopera1ef6112004-08-09 16:14:41 +0000823 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000824 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000825 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000826 signature for this factory function should match the signature
827 of the DocTest constructor.
828
Tim Peters8485b562004-08-04 18:46:34 +0000829 If the optional argument `recurse` is false, then `find` will
830 only examine the given object, and not any contained objects.
831 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000832 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000833 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000834 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000835 # _namefilter is undocumented, and exists only for temporary backward-
836 # compatibility support of testmod's deprecated isprivate mess.
837 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000838
839 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000840 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000841 """
842 Return a list of the DocTests that are defined by the given
843 object's docstring, or by any of its contained objects'
844 docstrings.
845
846 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000847 the given object. If the module is not specified or is None, then
848 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000849 correct module. The object's module is used:
850
851 - As a default namespace, if `globs` is not specified.
852 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000853 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000854 - To find the name of the file containing the object.
855 - To help find the line number of the object within its
856 file.
857
Tim Petersf3f57472004-08-08 06:11:48 +0000858 Contained objects whose module does not match `module` are ignored.
859
860 If `module` is False, no attempt to find the module will be made.
861 This is obscure, of use mostly in tests: if `module` is False, or
862 is None but cannot be found automatically, then all objects are
863 considered to belong to the (non-existent) module, so all contained
864 objects will (recursively) be searched for doctests.
865
Tim Peters8485b562004-08-04 18:46:34 +0000866 The globals for each DocTest is formed by combining `globs`
867 and `extraglobs` (bindings in `extraglobs` override bindings
868 in `globs`). A new copy of the globals dictionary is created
869 for each DocTest. If `globs` is not specified, then it
870 defaults to the module's `__dict__`, if specified, or {}
871 otherwise. If `extraglobs` is not specified, then it defaults
872 to {}.
873
Tim Peters8485b562004-08-04 18:46:34 +0000874 """
875 # If name was not specified, then extract it from the object.
876 if name is None:
877 name = getattr(obj, '__name__', None)
878 if name is None:
879 raise ValueError("DocTestFinder.find: name must be given "
880 "when obj.__name__ doesn't exist: %r" %
881 (type(obj),))
882
883 # Find the module that contains the given object (if obj is
884 # a module, then module=obj.). Note: this may fail, in which
885 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000886 if module is False:
887 module = None
888 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000889 module = inspect.getmodule(obj)
890
891 # Read the module's source code. This is used by
892 # DocTestFinder._find_lineno to find the line number for a
893 # given object's docstring.
894 try:
895 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
896 source_lines = linecache.getlines(file)
897 if not source_lines:
898 source_lines = None
899 except TypeError:
900 source_lines = None
901
902 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000903 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000904 if module is None:
905 globs = {}
906 else:
907 globs = module.__dict__.copy()
908 else:
909 globs = globs.copy()
910 if extraglobs is not None:
911 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000912
Tim Peters8485b562004-08-04 18:46:34 +0000913 # Recursively expore `obj`, extracting DocTests.
914 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000915 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000916 return tests
917
918 def _filter(self, obj, prefix, base):
919 """
920 Return true if the given object should not be examined.
921 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000922 return (self._namefilter is not None and
923 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000924
925 def _from_module(self, module, object):
926 """
927 Return true if the given object is defined in the given
928 module.
929 """
930 if module is None:
931 return True
932 elif inspect.isfunction(object):
933 return module.__dict__ is object.func_globals
934 elif inspect.isclass(object):
935 return module.__name__ == object.__module__
936 elif inspect.getmodule(object) is not None:
937 return module is inspect.getmodule(object)
938 elif hasattr(object, '__module__'):
939 return module.__name__ == object.__module__
940 elif isinstance(object, property):
941 return True # [XX] no way not be sure.
942 else:
943 raise ValueError("object must be a class or function")
944
Tim Petersf3f57472004-08-08 06:11:48 +0000945 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000946 """
947 Find tests for the given object and any contained objects, and
948 add them to `tests`.
949 """
950 if self._verbose:
951 print 'Finding tests in %s' % name
952
953 # If we've already processed this object, then ignore it.
954 if id(obj) in seen:
955 return
956 seen[id(obj)] = 1
957
958 # Find a test for this object, and add it to the list of tests.
959 test = self._get_test(obj, name, module, globs, source_lines)
960 if test is not None:
961 tests.append(test)
962
963 # Look for tests in a module's contained objects.
964 if inspect.ismodule(obj) and self._recurse:
965 for valname, val in obj.__dict__.items():
966 # Check if this contained object should be ignored.
967 if self._filter(val, name, valname):
968 continue
969 valname = '%s.%s' % (name, valname)
970 # Recurse to functions & classes.
971 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000972 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000973 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000974 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000975
976 # Look for tests in a module's __test__ dictionary.
977 if inspect.ismodule(obj) and self._recurse:
978 for valname, val in getattr(obj, '__test__', {}).items():
979 if not isinstance(valname, basestring):
980 raise ValueError("DocTestFinder.find: __test__ keys "
981 "must be strings: %r" %
982 (type(valname),))
983 if not (inspect.isfunction(val) or inspect.isclass(val) or
984 inspect.ismethod(val) or inspect.ismodule(val) or
985 isinstance(val, basestring)):
986 raise ValueError("DocTestFinder.find: __test__ values "
987 "must be strings, functions, methods, "
988 "classes, or modules: %r" %
989 (type(val),))
990 valname = '%s.%s' % (name, valname)
991 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000992 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000993
994 # Look for tests in a class's contained objects.
995 if inspect.isclass(obj) and self._recurse:
996 for valname, val in obj.__dict__.items():
997 # Check if this contained object should be ignored.
998 if self._filter(val, name, valname):
999 continue
1000 # Special handling for staticmethod/classmethod.
1001 if isinstance(val, staticmethod):
1002 val = getattr(obj, valname)
1003 if isinstance(val, classmethod):
1004 val = getattr(obj, valname).im_func
1005
1006 # Recurse to methods, properties, and nested classes.
1007 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001008 isinstance(val, property)) and
1009 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001010 valname = '%s.%s' % (name, valname)
1011 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001012 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001013
1014 def _get_test(self, obj, name, module, globs, source_lines):
1015 """
1016 Return a DocTest for the given object, if it defines a docstring;
1017 otherwise, return None.
1018 """
1019 # Extract the object's docstring. If it doesn't have one,
1020 # then return None (no test for this object).
1021 if isinstance(obj, basestring):
1022 docstring = obj
1023 else:
1024 try:
1025 if obj.__doc__ is None:
1026 return None
1027 docstring = str(obj.__doc__)
1028 except (TypeError, AttributeError):
1029 return None
1030
1031 # Don't bother if the docstring is empty.
1032 if not docstring:
1033 return None
1034
1035 # Find the docstring's location in the file.
1036 lineno = self._find_lineno(obj, source_lines)
1037
1038 # Return a DocTest for this object.
1039 if module is None:
1040 filename = None
1041 else:
1042 filename = getattr(module, '__file__', module.__name__)
Edward Lopera1ef6112004-08-09 16:14:41 +00001043 return self._parser.get_doctest(docstring, globs, name,
1044 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001045
1046 def _find_lineno(self, obj, source_lines):
1047 """
1048 Return a line number of the given object's docstring. Note:
1049 this method assumes that the object has a docstring.
1050 """
1051 lineno = None
1052
1053 # Find the line number for modules.
1054 if inspect.ismodule(obj):
1055 lineno = 0
1056
1057 # Find the line number for classes.
1058 # Note: this could be fooled if a class is defined multiple
1059 # times in a single file.
1060 if inspect.isclass(obj):
1061 if source_lines is None:
1062 return None
1063 pat = re.compile(r'^\s*class\s*%s\b' %
1064 getattr(obj, '__name__', '-'))
1065 for i, line in enumerate(source_lines):
1066 if pat.match(line):
1067 lineno = i
1068 break
1069
1070 # Find the line number for functions & methods.
1071 if inspect.ismethod(obj): obj = obj.im_func
1072 if inspect.isfunction(obj): obj = obj.func_code
1073 if inspect.istraceback(obj): obj = obj.tb_frame
1074 if inspect.isframe(obj): obj = obj.f_code
1075 if inspect.iscode(obj):
1076 lineno = getattr(obj, 'co_firstlineno', None)-1
1077
1078 # Find the line number where the docstring starts. Assume
1079 # that it's the first line that begins with a quote mark.
1080 # Note: this could be fooled by a multiline function
1081 # signature, where a continuation line begins with a quote
1082 # mark.
1083 if lineno is not None:
1084 if source_lines is None:
1085 return lineno+1
1086 pat = re.compile('(^|.*:)\s*\w*("|\')')
1087 for lineno in range(lineno, len(source_lines)):
1088 if pat.match(source_lines[lineno]):
1089 return lineno
1090
1091 # We couldn't find the line number.
1092 return None
1093
1094######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001095## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001096######################################################################
1097
Tim Peters8485b562004-08-04 18:46:34 +00001098class DocTestRunner:
1099 """
1100 A class used to run DocTest test cases, and accumulate statistics.
1101 The `run` method is used to process a single DocTest case. It
1102 returns a tuple `(f, t)`, where `t` is the number of test cases
1103 tried, and `f` is the number of test cases that failed.
1104
1105 >>> tests = DocTestFinder().find(_TestClass)
1106 >>> runner = DocTestRunner(verbose=False)
1107 >>> for test in tests:
1108 ... print runner.run(test)
1109 (0, 2)
1110 (0, 1)
1111 (0, 2)
1112 (0, 2)
1113
1114 The `summarize` method prints a summary of all the test cases that
1115 have been run by the runner, and returns an aggregated `(f, t)`
1116 tuple:
1117
1118 >>> runner.summarize(verbose=1)
1119 4 items passed all tests:
1120 2 tests in _TestClass
1121 2 tests in _TestClass.__init__
1122 2 tests in _TestClass.get
1123 1 tests in _TestClass.square
1124 7 tests in 4 items.
1125 7 passed and 0 failed.
1126 Test passed.
1127 (0, 7)
1128
1129 The aggregated number of tried examples and failed examples is
1130 also available via the `tries` and `failures` attributes:
1131
1132 >>> runner.tries
1133 7
1134 >>> runner.failures
1135 0
1136
1137 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001138 by an `OutputChecker`. This comparison may be customized with a
1139 number of option flags; see the documentation for `testmod` for
1140 more information. If the option flags are insufficient, then the
1141 comparison may also be customized by passing a subclass of
1142 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001143
1144 The test runner's display output can be controlled in two ways.
1145 First, an output function (`out) can be passed to
1146 `TestRunner.run`; this function will be called with strings that
1147 should be displayed. It defaults to `sys.stdout.write`. If
1148 capturing the output is not sufficient, then the display output
1149 can be also customized by subclassing DocTestRunner, and
1150 overriding the methods `report_start`, `report_success`,
1151 `report_unexpected_exception`, and `report_failure`.
1152 """
1153 # This divider string is used to separate failure messages, and to
1154 # separate sections of the summary.
1155 DIVIDER = "*" * 70
1156
Edward Loper34fcb142004-08-09 02:45:41 +00001157 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001158 """
1159 Create a new test runner.
1160
Edward Loper34fcb142004-08-09 02:45:41 +00001161 Optional keyword arg `checker` is the `OutputChecker` that
1162 should be used to compare the expected outputs and actual
1163 outputs of doctest examples.
1164
Tim Peters8485b562004-08-04 18:46:34 +00001165 Optional keyword arg 'verbose' prints lots of stuff if true,
1166 only failures if false; by default, it's true iff '-v' is in
1167 sys.argv.
1168
1169 Optional argument `optionflags` can be used to control how the
1170 test runner compares expected output to actual output, and how
1171 it displays failures. See the documentation for `testmod` for
1172 more information.
1173 """
Edward Loper34fcb142004-08-09 02:45:41 +00001174 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001175 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001176 verbose = '-v' in sys.argv
1177 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001178 self.optionflags = optionflags
1179
Tim Peters8485b562004-08-04 18:46:34 +00001180 # Keep track of the examples we've run.
1181 self.tries = 0
1182 self.failures = 0
1183 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001184
Tim Peters8485b562004-08-04 18:46:34 +00001185 # Create a fake output target for capturing doctest output.
1186 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001187
Tim Peters8485b562004-08-04 18:46:34 +00001188 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001189 # Reporting methods
1190 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001191
Tim Peters8485b562004-08-04 18:46:34 +00001192 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001193 """
Tim Peters8485b562004-08-04 18:46:34 +00001194 Report that the test runner is about to process the given
1195 example. (Only displays a message if verbose=True)
1196 """
1197 if self._verbose:
1198 out(_tag_msg("Trying", example.source) +
1199 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001200
Tim Peters8485b562004-08-04 18:46:34 +00001201 def report_success(self, out, test, example, got):
1202 """
1203 Report that the given example ran successfully. (Only
1204 displays a message if verbose=True)
1205 """
1206 if self._verbose:
1207 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001208
Tim Peters8485b562004-08-04 18:46:34 +00001209 def report_failure(self, out, test, example, got):
1210 """
1211 Report that the given example failed.
1212 """
1213 # Print an error message.
Edward Loper8e4a34b2004-08-12 02:34:27 +00001214 out(self._failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001215 self._checker.output_difference(example.want, got,
1216 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001217
Tim Peters8485b562004-08-04 18:46:34 +00001218 def report_unexpected_exception(self, out, test, example, exc_info):
1219 """
1220 Report that the given example raised an unexpected exception.
1221 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001222 out(self._failure_header(test, example) +
1223 _tag_msg("Exception raised", _exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001224
Edward Loper8e4a34b2004-08-12 02:34:27 +00001225 def _failure_header(self, test, example):
Tim Peters8485b562004-08-04 18:46:34 +00001226 s = (self.DIVIDER + "\n" +
1227 _tag_msg("Failure in example", example.source))
1228 if test.filename is None:
1229 # [XX] I'm not putting +1 here, to give the same output
1230 # as the old version. But I think it *should* go here.
1231 return s + ("from line #%s of %s\n" %
1232 (example.lineno, test.name))
1233 elif test.lineno is None:
1234 return s + ("from line #%s of %s in %s\n" %
1235 (example.lineno+1, test.name, test.filename))
1236 else:
1237 lineno = test.lineno+example.lineno+1
1238 return s + ("from line #%s of %s (%s)\n" %
1239 (lineno, test.filename, test.name))
Tim Peters7402f792001-10-02 03:53:41 +00001240
Tim Peters8485b562004-08-04 18:46:34 +00001241 #/////////////////////////////////////////////////////////////////
1242 # DocTest Running
1243 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001244
Tim Peters8485b562004-08-04 18:46:34 +00001245 # A regular expression for handling `want` strings that contain
Tim Peters41a65ea2004-08-13 03:55:05 +00001246 # expected exceptions. It divides `want` into three pieces:
1247 # - the pre-exception output (`want`)
1248 # - the traceback header line (`hdr`)
1249 # - the exception message (`msg`), as generated by
1250 # traceback.format_exception_only()
1251 # `msg` may have multiple lines. We assume/require that the
1252 # exception message is the first non-indented line starting with a word
1253 # character following the traceback header line.
1254 _EXCEPTION_RE = re.compile(r"""
1255 (?P<want> .*?) # suck up everything until traceback header
1256 # Grab the traceback header. Different versions of Python have
1257 # said different things on the first traceback line.
1258 ^(?P<hdr> Traceback\ \(
1259 (?: most\ recent\ call\ last
1260 | innermost\ last
1261 ) \) :
1262 )
1263 \s* $ # toss trailing whitespace on traceback header
1264 .*? # don't blink: absorb stuff until a line *starts* with \w
1265 ^ (?P<msg> \w+ .*)
1266 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001267
Tim Peters8485b562004-08-04 18:46:34 +00001268 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001269 """
Tim Peters8485b562004-08-04 18:46:34 +00001270 Run the examples in `test`. Write the outcome of each example
1271 with one of the `DocTestRunner.report_*` methods, using the
1272 writer function `out`. `compileflags` is the set of compiler
1273 flags that should be used to execute examples. Return a tuple
1274 `(f, t)`, where `t` is the number of examples tried, and `f`
1275 is the number of examples that failed. The examples are run
1276 in the namespace `test.globs`.
1277 """
1278 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001279 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001280
1281 # Save the option flags (since option directives can be used
1282 # to modify them).
1283 original_optionflags = self.optionflags
1284
1285 # Process each example.
1286 for example in test.examples:
Edward Loper74bca7a2004-08-12 02:27:44 +00001287 # Merge in the example's options.
1288 self.optionflags = original_optionflags
1289 if example.options:
1290 for (optionflag, val) in example.options.items():
1291 if val:
1292 self.optionflags |= optionflag
1293 else:
1294 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001295
1296 # Record that we started this example.
1297 tries += 1
1298 self.report_start(out, test, example)
1299
1300 # Run the example in the given context (globs), and record
1301 # any exception that gets raised. (But don't intercept
1302 # keyboard interrupts.)
1303 try:
Tim Peters208ca702004-08-09 04:12:36 +00001304 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001305 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001306 compileflags, 1) in test.globs
1307 exception = None
1308 except KeyboardInterrupt:
1309 raise
1310 except:
1311 exception = sys.exc_info()
1312
Tim Peters208ca702004-08-09 04:12:36 +00001313 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001314 self._fakeout.truncate(0)
1315
1316 # If the example executed without raising any exceptions,
1317 # then verify its output and report its outcome.
1318 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001319 if self._checker.check_output(example.want, got,
1320 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001321 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001322 else:
Tim Peters8485b562004-08-04 18:46:34 +00001323 self.report_failure(out, test, example, got)
1324 failures += 1
1325
1326 # If the example raised an exception, then check if it was
1327 # expected.
1328 else:
1329 exc_info = sys.exc_info()
1330 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1331
1332 # Search the `want` string for an exception. If we don't
1333 # find one, then report an unexpected exception.
1334 m = self._EXCEPTION_RE.match(example.want)
1335 if m is None:
1336 self.report_unexpected_exception(out, test, example,
1337 exc_info)
1338 failures += 1
1339 else:
Tim Peters41a65ea2004-08-13 03:55:05 +00001340 e_want, e_msg = m.group('want', 'msg')
Tim Peters8485b562004-08-04 18:46:34 +00001341 # The test passes iff the pre-exception output and
1342 # the exception description match the values given
1343 # in `want`.
Tim Peters41a65ea2004-08-13 03:55:05 +00001344 if (self._checker.check_output(e_want, got,
Edward Loper34fcb142004-08-09 02:45:41 +00001345 self.optionflags) and
Tim Peters41a65ea2004-08-13 03:55:05 +00001346 self._checker.check_output(e_msg, exc_msg,
Edward Loper34fcb142004-08-09 02:45:41 +00001347 self.optionflags)):
Tim Peters8485b562004-08-04 18:46:34 +00001348 self.report_success(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001349 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001350 else:
1351 self.report_failure(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001352 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001353 failures += 1
1354
1355 # Restore the option flags (in case they were modified)
1356 self.optionflags = original_optionflags
1357
1358 # Record and return the number of failures and tries.
1359 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001360 return failures, tries
1361
Tim Peters8485b562004-08-04 18:46:34 +00001362 def __record_outcome(self, test, f, t):
1363 """
1364 Record the fact that the given DocTest (`test`) generated `f`
1365 failures out of `t` tried examples.
1366 """
1367 f2, t2 = self._name2ft.get(test.name, (0,0))
1368 self._name2ft[test.name] = (f+f2, t+t2)
1369 self.failures += f
1370 self.tries += t
1371
1372 def run(self, test, compileflags=None, out=None, clear_globs=True):
1373 """
1374 Run the examples in `test`, and display the results using the
1375 writer function `out`.
1376
1377 The examples are run in the namespace `test.globs`. If
1378 `clear_globs` is true (the default), then this namespace will
1379 be cleared after the test runs, to help with garbage
1380 collection. If you would like to examine the namespace after
1381 the test completes, then use `clear_globs=False`.
1382
1383 `compileflags` gives the set of flags that should be used by
1384 the Python compiler when running the examples. If not
1385 specified, then it will default to the set of future-import
1386 flags that apply to `globs`.
1387
1388 The output of each example is checked using
1389 `DocTestRunner.check_output`, and the results are formatted by
1390 the `DocTestRunner.report_*` methods.
1391 """
1392 if compileflags is None:
1393 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001394
Tim Peters6c542b72004-08-09 16:43:36 +00001395 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001396 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001397 out = save_stdout.write
1398 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001399
Tim Peters6c542b72004-08-09 16:43:36 +00001400 # Patch pdb.set_trace to restore sys.stdout, so that interactive
1401 # debugging output is visible (not still redirected to self._fakeout).
1402 # Note that we run "the real" pdb.set_trace (captured at doctest
1403 # import time) in our replacement. Because the current run() may
1404 # run another doctest (and so on), the current pdb.set_trace may be
1405 # our set_trace function, which changes sys.stdout. If we called
1406 # a chain of those, we wouldn't be left with the save_stdout
1407 # *this* run() invocation wants.
Jim Fulton356fd192004-08-09 11:34:47 +00001408 def set_trace():
Tim Peters6c542b72004-08-09 16:43:36 +00001409 sys.stdout = save_stdout
Jim Fulton356fd192004-08-09 11:34:47 +00001410 real_pdb_set_trace()
1411
Tim Peters6c542b72004-08-09 16:43:36 +00001412 save_set_trace = pdb.set_trace
1413 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001414 try:
Tim Peters8485b562004-08-04 18:46:34 +00001415 return self.__run(test, compileflags, out)
1416 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001417 sys.stdout = save_stdout
1418 pdb.set_trace = save_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001419 if clear_globs:
1420 test.globs.clear()
1421
1422 #/////////////////////////////////////////////////////////////////
1423 # Summarization
1424 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001425 def summarize(self, verbose=None):
1426 """
Tim Peters8485b562004-08-04 18:46:34 +00001427 Print a summary of all the test cases that have been run by
1428 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1429 the total number of failed examples, and `t` is the total
1430 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001431
Tim Peters8485b562004-08-04 18:46:34 +00001432 The optional `verbose` argument controls how detailed the
1433 summary is. If the verbosity is not specified, then the
1434 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001435 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001436 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001437 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001438 notests = []
1439 passed = []
1440 failed = []
1441 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001442 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001443 name, (f, t) = x
1444 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001445 totalt += t
1446 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001447 if t == 0:
1448 notests.append(name)
1449 elif f == 0:
1450 passed.append( (name, t) )
1451 else:
1452 failed.append(x)
1453 if verbose:
1454 if notests:
1455 print len(notests), "items had no tests:"
1456 notests.sort()
1457 for thing in notests:
1458 print " ", thing
1459 if passed:
1460 print len(passed), "items passed all tests:"
1461 passed.sort()
1462 for thing, count in passed:
1463 print " %3d tests in %s" % (count, thing)
1464 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001465 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001466 print len(failed), "items had failures:"
1467 failed.sort()
1468 for thing, (f, t) in failed:
1469 print " %3d of %3d in %s" % (f, t, thing)
1470 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001471 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001472 print totalt - totalf, "passed and", totalf, "failed."
1473 if totalf:
1474 print "***Test Failed***", totalf, "failures."
1475 elif verbose:
1476 print "Test passed."
1477 return totalf, totalt
1478
Edward Loper34fcb142004-08-09 02:45:41 +00001479class OutputChecker:
1480 """
1481 A class used to check the whether the actual output from a doctest
1482 example matches the expected output. `OutputChecker` defines two
1483 methods: `check_output`, which compares a given pair of outputs,
1484 and returns true if they match; and `output_difference`, which
1485 returns a string describing the differences between two outputs.
1486 """
1487 def check_output(self, want, got, optionflags):
1488 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001489 Return True iff the actual output from an example (`got`)
1490 matches the expected output (`want`). These strings are
1491 always considered to match if they are identical; but
1492 depending on what option flags the test runner is using,
1493 several non-exact match types are also possible. See the
1494 documentation for `TestRunner` for more information about
1495 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001496 """
1497 # Handle the common case first, for efficiency:
1498 # if they're string-identical, always return true.
1499 if got == want:
1500 return True
1501
1502 # The values True and False replaced 1 and 0 as the return
1503 # value for boolean comparisons in Python 2.3.
1504 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1505 if (got,want) == ("True\n", "1\n"):
1506 return True
1507 if (got,want) == ("False\n", "0\n"):
1508 return True
1509
1510 # <BLANKLINE> can be used as a special sequence to signify a
1511 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1512 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1513 # Replace <BLANKLINE> in want with a blank line.
1514 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1515 '', want)
1516 # If a line in got contains only spaces, then remove the
1517 # spaces.
1518 got = re.sub('(?m)^\s*?$', '', got)
1519 if got == want:
1520 return True
1521
1522 # This flag causes doctest to ignore any differences in the
1523 # contents of whitespace strings. Note that this can be used
1524 # in conjunction with the ELLISPIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001525 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001526 got = ' '.join(got.split())
1527 want = ' '.join(want.split())
1528 if got == want:
1529 return True
1530
1531 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001532 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001533 if optionflags & ELLIPSIS:
Tim Peters26b3ebb2004-08-19 08:10:08 +00001534 if ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001535 return True
1536
1537 # We didn't find any match; return false.
1538 return False
1539
1540 def output_difference(self, want, got, optionflags):
1541 """
1542 Return a string describing the differences between the
Edward Loper74bca7a2004-08-12 02:27:44 +00001543 expected output for an example (`want`) and the actual output
1544 (`got`). `optionflags` is the set of option flags used to
1545 compare `want` and `got`. `indent` is the indentation of the
1546 original example.
Edward Loper34fcb142004-08-09 02:45:41 +00001547 """
Edward Loper68ba9a62004-08-12 02:43:49 +00001548 # If <BLANKLINE>s are being used, then replace blank lines
1549 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001550 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001551 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001552
1553 # Check if we should use diff. Don't use diff if the actual
1554 # or expected outputs are too short, or if the expected output
1555 # contains an ellipsis marker.
1556 if ((optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and
1557 want.count('\n') > 2 and got.count('\n') > 2 and
1558 not (optionflags & ELLIPSIS and '...' in want)):
1559 # Split want & got into lines.
1560 want_lines = [l+'\n' for l in want.split('\n')]
1561 got_lines = [l+'\n' for l in got.split('\n')]
1562 # Use difflib to find their differences.
1563 if optionflags & UNIFIED_DIFF:
1564 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1565 fromfile='Expected', tofile='Got')
1566 kind = 'unified'
1567 elif optionflags & CONTEXT_DIFF:
1568 diff = difflib.context_diff(want_lines, got_lines, n=2,
1569 fromfile='Expected', tofile='Got')
1570 kind = 'context'
1571 else:
1572 assert 0, 'Bad diff option'
1573 # Remove trailing whitespace on diff output.
1574 diff = [line.rstrip() + '\n' for line in diff]
1575 return _tag_msg("Differences (" + kind + " diff)",
1576 ''.join(diff))
1577
1578 # If we're not using diff, then simply list the expected
1579 # output followed by the actual output.
1580 return (_tag_msg("Expected", want or "Nothing") +
1581 _tag_msg("Got", got))
1582
Tim Peters19397e52004-08-06 22:02:59 +00001583class DocTestFailure(Exception):
1584 """A DocTest example has failed in debugging mode.
1585
1586 The exception instance has variables:
1587
1588 - test: the DocTest object being run
1589
1590 - excample: the Example object that failed
1591
1592 - got: the actual output
1593 """
1594 def __init__(self, test, example, got):
1595 self.test = test
1596 self.example = example
1597 self.got = got
1598
1599 def __str__(self):
1600 return str(self.test)
1601
1602class UnexpectedException(Exception):
1603 """A DocTest example has encountered an unexpected exception
1604
1605 The exception instance has variables:
1606
1607 - test: the DocTest object being run
1608
1609 - excample: the Example object that failed
1610
1611 - exc_info: the exception info
1612 """
1613 def __init__(self, test, example, exc_info):
1614 self.test = test
1615 self.example = example
1616 self.exc_info = exc_info
1617
1618 def __str__(self):
1619 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001620
Tim Peters19397e52004-08-06 22:02:59 +00001621class DebugRunner(DocTestRunner):
1622 r"""Run doc tests but raise an exception as soon as there is a failure.
1623
1624 If an unexpected exception occurs, an UnexpectedException is raised.
1625 It contains the test, the example, and the original exception:
1626
1627 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001628 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1629 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001630 >>> try:
1631 ... runner.run(test)
1632 ... except UnexpectedException, failure:
1633 ... pass
1634
1635 >>> failure.test is test
1636 True
1637
1638 >>> failure.example.want
1639 '42\n'
1640
1641 >>> exc_info = failure.exc_info
1642 >>> raise exc_info[0], exc_info[1], exc_info[2]
1643 Traceback (most recent call last):
1644 ...
1645 KeyError
1646
1647 We wrap the original exception to give the calling application
1648 access to the test and example information.
1649
1650 If the output doesn't match, then a DocTestFailure is raised:
1651
Edward Lopera1ef6112004-08-09 16:14:41 +00001652 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001653 ... >>> x = 1
1654 ... >>> x
1655 ... 2
1656 ... ''', {}, 'foo', 'foo.py', 0)
1657
1658 >>> try:
1659 ... runner.run(test)
1660 ... except DocTestFailure, failure:
1661 ... pass
1662
1663 DocTestFailure objects provide access to the test:
1664
1665 >>> failure.test is test
1666 True
1667
1668 As well as to the example:
1669
1670 >>> failure.example.want
1671 '2\n'
1672
1673 and the actual output:
1674
1675 >>> failure.got
1676 '1\n'
1677
1678 If a failure or error occurs, the globals are left intact:
1679
1680 >>> del test.globs['__builtins__']
1681 >>> test.globs
1682 {'x': 1}
1683
Edward Lopera1ef6112004-08-09 16:14:41 +00001684 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001685 ... >>> x = 2
1686 ... >>> raise KeyError
1687 ... ''', {}, 'foo', 'foo.py', 0)
1688
1689 >>> runner.run(test)
1690 Traceback (most recent call last):
1691 ...
1692 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001693
Tim Peters19397e52004-08-06 22:02:59 +00001694 >>> del test.globs['__builtins__']
1695 >>> test.globs
1696 {'x': 2}
1697
1698 But the globals are cleared if there is no error:
1699
Edward Lopera1ef6112004-08-09 16:14:41 +00001700 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001701 ... >>> x = 2
1702 ... ''', {}, 'foo', 'foo.py', 0)
1703
1704 >>> runner.run(test)
1705 (0, 1)
1706
1707 >>> test.globs
1708 {}
1709
1710 """
1711
1712 def run(self, test, compileflags=None, out=None, clear_globs=True):
1713 r = DocTestRunner.run(self, test, compileflags, out, False)
1714 if clear_globs:
1715 test.globs.clear()
1716 return r
1717
1718 def report_unexpected_exception(self, out, test, example, exc_info):
1719 raise UnexpectedException(test, example, exc_info)
1720
1721 def report_failure(self, out, test, example, got):
1722 raise DocTestFailure(test, example, got)
1723
Tim Peters8485b562004-08-04 18:46:34 +00001724######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001725## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001726######################################################################
1727# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001728
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001729def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001730 report=True, optionflags=0, extraglobs=None,
1731 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001732 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001733 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001734
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001735 Test examples in docstrings in functions and classes reachable
1736 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001737 with m.__doc__. Unless isprivate is specified, private names
1738 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001739
1740 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001741 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001742 function and class docstrings are tested even if the name is private;
1743 strings are tested directly, as if they were docstrings.
1744
1745 Return (#failures, #tests).
1746
1747 See doctest.__doc__ for an overview.
1748
1749 Optional keyword arg "name" gives the name of the module; by default
1750 use m.__name__.
1751
1752 Optional keyword arg "globs" gives a dict to be used as the globals
1753 when executing examples; by default, use m.__dict__. A copy of this
1754 dict is actually used for each docstring, so that each docstring's
1755 examples start with a clean slate.
1756
Tim Peters8485b562004-08-04 18:46:34 +00001757 Optional keyword arg "extraglobs" gives a dictionary that should be
1758 merged into the globals that are used to execute examples. By
1759 default, no extra globals are used. This is new in 2.4.
1760
Tim Peters8a7d2d52001-01-16 07:10:57 +00001761 Optional keyword arg "verbose" prints lots of stuff if true, prints
1762 only failures if false; by default, it's true iff "-v" is in sys.argv.
1763
Tim Peters8a7d2d52001-01-16 07:10:57 +00001764 Optional keyword arg "report" prints a summary at the end when true,
1765 else prints nothing at the end. In verbose mode, the summary is
1766 detailed, else very brief (in fact, empty if all tests passed).
1767
Tim Peters6ebe61f2003-06-27 20:48:05 +00001768 Optional keyword arg "optionflags" or's together module constants,
1769 and defaults to 0. This is new in 2.3. Possible values:
1770
1771 DONT_ACCEPT_TRUE_FOR_1
1772 By default, if an expected output block contains just "1",
1773 an actual output block containing just "True" is considered
1774 to be a match, and similarly for "0" versus "False". When
1775 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1776 is allowed.
1777
Tim Peters8485b562004-08-04 18:46:34 +00001778 DONT_ACCEPT_BLANKLINE
1779 By default, if an expected output block contains a line
1780 containing only the string "<BLANKLINE>", then that line
1781 will match a blank line in the actual output. When
1782 DONT_ACCEPT_BLANKLINE is specified, this substitution is
1783 not allowed.
1784
1785 NORMALIZE_WHITESPACE
1786 When NORMALIZE_WHITESPACE is specified, all sequences of
1787 whitespace are treated as equal. I.e., any sequence of
1788 whitespace within the expected output will match any
1789 sequence of whitespace within the actual output.
1790
1791 ELLIPSIS
1792 When ELLIPSIS is specified, then an ellipsis marker
1793 ("...") in the expected output can match any substring in
1794 the actual output.
1795
1796 UNIFIED_DIFF
1797 When UNIFIED_DIFF is specified, failures that involve
1798 multi-line expected and actual outputs will be displayed
1799 using a unified diff.
1800
1801 CONTEXT_DIFF
1802 When CONTEXT_DIFF is specified, failures that involve
1803 multi-line expected and actual outputs will be displayed
1804 using a context diff.
Tim Peters19397e52004-08-06 22:02:59 +00001805
1806 Optional keyword arg "raise_on_error" raises an exception on the
1807 first unexpected exception or failure. This allows failures to be
1808 post-mortem debugged.
1809
Tim Petersf727c6c2004-08-08 01:48:59 +00001810 Deprecated in Python 2.4:
1811 Optional keyword arg "isprivate" specifies a function used to
1812 determine whether a name is private. The default function is
1813 treat all functions as public. Optionally, "isprivate" can be
1814 set to doctest.is_private to skip over functions marked as private
1815 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001816 """
1817
1818 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001819 Advanced tomfoolery: testmod runs methods of a local instance of
1820 class doctest.Tester, then merges the results into (or creates)
1821 global Tester instance doctest.master. Methods of doctest.master
1822 can be called directly too, if you want to do something unusual.
1823 Passing report=0 to testmod is especially useful then, to delay
1824 displaying a summary. Invoke doctest.master.summarize(verbose)
1825 when you're done fiddling.
1826 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001827 if isprivate is not None:
1828 warnings.warn("the isprivate argument is deprecated; "
1829 "examine DocTestFinder.find() lists instead",
1830 DeprecationWarning)
1831
Tim Peters8485b562004-08-04 18:46:34 +00001832 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001833 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001834 # DWA - m will still be None if this wasn't invoked from the command
1835 # line, in which case the following TypeError is about as good an error
1836 # as we should expect
1837 m = sys.modules.get('__main__')
1838
Tim Peters8485b562004-08-04 18:46:34 +00001839 # Check that we were actually given a module.
1840 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001841 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001842
1843 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001844 if name is None:
1845 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001846
1847 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001848 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001849
1850 if raise_on_error:
1851 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1852 else:
1853 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1854
Tim Peters8485b562004-08-04 18:46:34 +00001855 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1856 runner.run(test)
1857
Tim Peters8a7d2d52001-01-16 07:10:57 +00001858 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001859 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001860
Tim Peters8485b562004-08-04 18:46:34 +00001861 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001862
Tim Peters8485b562004-08-04 18:46:34 +00001863def run_docstring_examples(f, globs, verbose=False, name="NoName",
1864 compileflags=None, optionflags=0):
1865 """
1866 Test examples in the given object's docstring (`f`), using `globs`
1867 as globals. Optional argument `name` is used in failure messages.
1868 If the optional argument `verbose` is true, then generate output
1869 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001870
Tim Peters8485b562004-08-04 18:46:34 +00001871 `compileflags` gives the set of flags that should be used by the
1872 Python compiler when running the examples. If not specified, then
1873 it will default to the set of future-import flags that apply to
1874 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001875
Tim Peters8485b562004-08-04 18:46:34 +00001876 Optional keyword arg `optionflags` specifies options for the
1877 testing and output. See the documentation for `testmod` for more
1878 information.
1879 """
1880 # Find, parse, and run all tests in the given module.
1881 finder = DocTestFinder(verbose=verbose, recurse=False)
1882 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1883 for test in finder.find(f, name, globs=globs):
1884 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001885
Tim Peters8485b562004-08-04 18:46:34 +00001886######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001887## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001888######################################################################
1889# This is provided only for backwards compatibility. It's not
1890# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001891
Tim Peters8485b562004-08-04 18:46:34 +00001892class Tester:
1893 def __init__(self, mod=None, globs=None, verbose=None,
1894 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001895
1896 warnings.warn("class Tester is deprecated; "
1897 "use class doctest.DocTestRunner instead",
1898 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001899 if mod is None and globs is None:
1900 raise TypeError("Tester.__init__: must specify mod or globs")
1901 if mod is not None and not _ismodule(mod):
1902 raise TypeError("Tester.__init__: mod must be a module; %r" %
1903 (mod,))
1904 if globs is None:
1905 globs = mod.__dict__
1906 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001907
Tim Peters8485b562004-08-04 18:46:34 +00001908 self.verbose = verbose
1909 self.isprivate = isprivate
1910 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001911 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001912 self.testrunner = DocTestRunner(verbose=verbose,
1913 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001914
Tim Peters8485b562004-08-04 18:46:34 +00001915 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001916 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001917 if self.verbose:
1918 print "Running string", name
1919 (f,t) = self.testrunner.run(test)
1920 if self.verbose:
1921 print f, "of", t, "examples failed in string", name
1922 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001923
Tim Petersf3f57472004-08-08 06:11:48 +00001924 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001925 f = t = 0
1926 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001927 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001928 for test in tests:
1929 (f2, t2) = self.testrunner.run(test)
1930 (f,t) = (f+f2, t+t2)
1931 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001932
Tim Peters8485b562004-08-04 18:46:34 +00001933 def rundict(self, d, name, module=None):
1934 import new
1935 m = new.module(name)
1936 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001937 if module is None:
1938 module = False
1939 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001940
Tim Peters8485b562004-08-04 18:46:34 +00001941 def run__test__(self, d, name):
1942 import new
1943 m = new.module(name)
1944 m.__test__ = d
1945 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001946
Tim Peters8485b562004-08-04 18:46:34 +00001947 def summarize(self, verbose=None):
1948 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001949
Tim Peters8485b562004-08-04 18:46:34 +00001950 def merge(self, other):
1951 d = self.testrunner._name2ft
1952 for name, (f, t) in other.testrunner._name2ft.items():
1953 if name in d:
1954 print "*** Tester.merge: '" + name + "' in both" \
1955 " testers; summing outcomes."
1956 f2, t2 = d[name]
1957 f = f + f2
1958 t = t + t2
1959 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001960
Tim Peters8485b562004-08-04 18:46:34 +00001961######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001962## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001963######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001964
Tim Peters19397e52004-08-06 22:02:59 +00001965class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001966
Edward Loper34fcb142004-08-09 02:45:41 +00001967 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
1968 checker=None):
Jim Fultona643b652004-07-14 19:06:50 +00001969 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00001970 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00001971 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00001972 self._dt_test = test
1973 self._dt_setUp = setUp
1974 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00001975
Jim Fultona643b652004-07-14 19:06:50 +00001976 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00001977 if self._dt_setUp is not None:
1978 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00001979
1980 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00001981 if self._dt_tearDown is not None:
1982 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00001983
1984 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00001985 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00001986 old = sys.stdout
1987 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00001988 runner = DocTestRunner(optionflags=self._dt_optionflags,
1989 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001990
Jim Fultona643b652004-07-14 19:06:50 +00001991 try:
Tim Peters19397e52004-08-06 22:02:59 +00001992 runner.DIVIDER = "-"*70
1993 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00001994 finally:
1995 sys.stdout = old
1996
1997 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00001998 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00001999
Tim Peters19397e52004-08-06 22:02:59 +00002000 def format_failure(self, err):
2001 test = self._dt_test
2002 if test.lineno is None:
2003 lineno = 'unknown line number'
2004 else:
2005 lineno = 'line %s' % test.lineno
2006 lname = '.'.join(test.name.split('.')[-1:])
2007 return ('Failed doctest test for %s\n'
2008 ' File "%s", line %s, in %s\n\n%s'
2009 % (test.name, test.filename, lineno, lname, err)
2010 )
2011
2012 def debug(self):
2013 r"""Run the test case without results and without catching exceptions
2014
2015 The unit test framework includes a debug method on test cases
2016 and test suites to support post-mortem debugging. The test code
2017 is run in such a way that errors are not caught. This way a
2018 caller can catch the errors and initiate post-mortem debugging.
2019
2020 The DocTestCase provides a debug method that raises
2021 UnexpectedException errors if there is an unexepcted
2022 exception:
2023
Edward Lopera1ef6112004-08-09 16:14:41 +00002024 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002025 ... {}, 'foo', 'foo.py', 0)
2026 >>> case = DocTestCase(test)
2027 >>> try:
2028 ... case.debug()
2029 ... except UnexpectedException, failure:
2030 ... pass
2031
2032 The UnexpectedException contains the test, the example, and
2033 the original exception:
2034
2035 >>> failure.test is test
2036 True
2037
2038 >>> failure.example.want
2039 '42\n'
2040
2041 >>> exc_info = failure.exc_info
2042 >>> raise exc_info[0], exc_info[1], exc_info[2]
2043 Traceback (most recent call last):
2044 ...
2045 KeyError
2046
2047 If the output doesn't match, then a DocTestFailure is raised:
2048
Edward Lopera1ef6112004-08-09 16:14:41 +00002049 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002050 ... >>> x = 1
2051 ... >>> x
2052 ... 2
2053 ... ''', {}, 'foo', 'foo.py', 0)
2054 >>> case = DocTestCase(test)
2055
2056 >>> try:
2057 ... case.debug()
2058 ... except DocTestFailure, failure:
2059 ... pass
2060
2061 DocTestFailure objects provide access to the test:
2062
2063 >>> failure.test is test
2064 True
2065
2066 As well as to the example:
2067
2068 >>> failure.example.want
2069 '2\n'
2070
2071 and the actual output:
2072
2073 >>> failure.got
2074 '1\n'
2075
2076 """
2077
Edward Loper34fcb142004-08-09 02:45:41 +00002078 runner = DebugRunner(optionflags=self._dt_optionflags,
2079 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002080 runner.run(self._dt_test, out=nooutput)
Jim Fultona643b652004-07-14 19:06:50 +00002081
2082 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002083 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002084
2085 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002086 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002087 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2088
2089 __str__ = __repr__
2090
2091 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002092 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002093
Tim Peters19397e52004-08-06 22:02:59 +00002094def nooutput(*args):
2095 pass
Jim Fultona643b652004-07-14 19:06:50 +00002096
Tim Peters19397e52004-08-06 22:02:59 +00002097def DocTestSuite(module=None, globs=None, extraglobs=None,
2098 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002099 setUp=lambda: None, tearDown=lambda: None,
2100 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002101 """
Tim Peters19397e52004-08-06 22:02:59 +00002102 Convert doctest tests for a mudule to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002103
Tim Peters19397e52004-08-06 22:02:59 +00002104 This converts each documentation string in a module that
2105 contains doctest tests to a unittest test case. If any of the
2106 tests in a doc string fail, then the test case fails. An exception
2107 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002108 (sometimes approximate) line number.
2109
Tim Peters19397e52004-08-06 22:02:59 +00002110 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002111 can be either a module or a module name.
2112
2113 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002114 """
Jim Fultona643b652004-07-14 19:06:50 +00002115
Tim Peters8485b562004-08-04 18:46:34 +00002116 if test_finder is None:
2117 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002118
Tim Peters19397e52004-08-06 22:02:59 +00002119 module = _normalize_module(module)
2120 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2121 if globs is None:
2122 globs = module.__dict__
2123 if not tests: # [XX] why do we want to do this?
2124 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002125
2126 tests.sort()
2127 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002128 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002129 if len(test.examples) == 0:
2130 continue
Tim Peters8485b562004-08-04 18:46:34 +00002131 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002132 filename = module.__file__
2133 if filename.endswith(".pyc"):
2134 filename = filename[:-1]
2135 elif filename.endswith(".pyo"):
2136 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002137 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002138 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2139 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002140
2141 return suite
2142
2143class DocFileCase(DocTestCase):
2144
2145 def id(self):
2146 return '_'.join(self._dt_test.name.split('.'))
2147
2148 def __repr__(self):
2149 return self._dt_test.filename
2150 __str__ = __repr__
2151
2152 def format_failure(self, err):
2153 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2154 % (self._dt_test.name, self._dt_test.filename, err)
2155 )
2156
2157def DocFileTest(path, package=None, globs=None,
2158 setUp=None, tearDown=None,
2159 optionflags=0):
2160 package = _normalize_module(package)
2161 name = path.split('/')[-1]
2162 dir = os.path.split(package.__file__)[0]
2163 path = os.path.join(dir, *(path.split('/')))
2164 doc = open(path).read()
2165
2166 if globs is None:
2167 globs = {}
2168
Edward Lopera1ef6112004-08-09 16:14:41 +00002169 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002170
2171 return DocFileCase(test, optionflags, setUp, tearDown)
2172
2173def DocFileSuite(*paths, **kw):
2174 """Creates a suite of doctest files.
2175
2176 One or more text file paths are given as strings. These should
2177 use "/" characters to separate path segments. Paths are relative
2178 to the directory of the calling module, or relative to the package
2179 passed as a keyword argument.
2180
2181 A number of options may be provided as keyword arguments:
2182
2183 package
2184 The name of a Python package. Text-file paths will be
2185 interpreted relative to the directory containing this package.
2186 The package may be supplied as a package object or as a dotted
2187 package name.
2188
2189 setUp
2190 The name of a set-up function. This is called before running the
2191 tests in each file.
2192
2193 tearDown
2194 The name of a tear-down function. This is called after running the
2195 tests in each file.
2196
2197 globs
2198 A dictionary containing initial global variables for the tests.
2199 """
2200 suite = unittest.TestSuite()
2201
2202 # We do this here so that _normalize_module is called at the right
2203 # level. If it were called in DocFileTest, then this function
2204 # would be the caller and we might guess the package incorrectly.
2205 kw['package'] = _normalize_module(kw.get('package'))
2206
2207 for path in paths:
2208 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002209
Tim Petersdb3756d2003-06-29 05:30:48 +00002210 return suite
2211
Tim Peters8485b562004-08-04 18:46:34 +00002212######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002213## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002214######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002215
Tim Peters19397e52004-08-06 22:02:59 +00002216def script_from_examples(s):
2217 r"""Extract script from text with examples.
2218
2219 Converts text with examples to a Python script. Example input is
2220 converted to regular code. Example output and all other words
2221 are converted to comments:
2222
2223 >>> text = '''
2224 ... Here are examples of simple math.
2225 ...
2226 ... Python has super accurate integer addition
2227 ...
2228 ... >>> 2 + 2
2229 ... 5
2230 ...
2231 ... And very friendly error messages:
2232 ...
2233 ... >>> 1/0
2234 ... To Infinity
2235 ... And
2236 ... Beyond
2237 ...
2238 ... You can use logic if you want:
2239 ...
2240 ... >>> if 0:
2241 ... ... blah
2242 ... ... blah
2243 ... ...
2244 ...
2245 ... Ho hum
2246 ... '''
2247
2248 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002249 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002250 #
Edward Lopera5db6002004-08-12 02:41:30 +00002251 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002252 #
2253 2 + 2
2254 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002255 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002256 #
Edward Lopera5db6002004-08-12 02:41:30 +00002257 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002258 #
2259 1/0
2260 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002261 ## To Infinity
2262 ## And
2263 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002264 #
Edward Lopera5db6002004-08-12 02:41:30 +00002265 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002266 #
2267 if 0:
2268 blah
2269 blah
2270 <BLANKLINE>
2271 #
Edward Lopera5db6002004-08-12 02:41:30 +00002272 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002273 """
2274
Edward Lopera1ef6112004-08-09 16:14:41 +00002275 return DocTestParser().get_program(s)
Tim Peters19397e52004-08-06 22:02:59 +00002276
Tim Peters8485b562004-08-04 18:46:34 +00002277def _want_comment(example):
2278 """
Tim Peters19397e52004-08-06 22:02:59 +00002279 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002280 """
Jim Fultona643b652004-07-14 19:06:50 +00002281 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002282 want = example.want
2283 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002284 if want[-1] == '\n':
2285 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002286 want = "\n# ".join(want.split("\n"))
2287 want = "\n# Expected:\n# %s" % want
2288 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002289
2290def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002291 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002292
2293 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002294 test to be debugged and the name (within the module) of the object
2295 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002296 """
Tim Peters8485b562004-08-04 18:46:34 +00002297 module = _normalize_module(module)
2298 tests = DocTestFinder().find(module)
2299 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002300 if not test:
2301 raise ValueError(name, "not found in tests")
2302 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002303 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002304 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002305
Jim Fultona643b652004-07-14 19:06:50 +00002306def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002307 """Debug a single doctest docstring, in argument `src`'"""
2308 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002309 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002310
Jim Fultona643b652004-07-14 19:06:50 +00002311def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002312 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002313 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002314
Tim Petersdb3756d2003-06-29 05:30:48 +00002315 srcfilename = tempfile.mktemp("doctestdebug.py")
Tim Peters8485b562004-08-04 18:46:34 +00002316 f = open(srcfilename, 'w')
2317 f.write(src)
2318 f.close()
2319
Jim Fultona643b652004-07-14 19:06:50 +00002320 if globs:
2321 globs = globs.copy()
2322 else:
2323 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002324
Tim Peters8485b562004-08-04 18:46:34 +00002325 if pm:
2326 try:
2327 execfile(srcfilename, globs, globs)
2328 except:
2329 print sys.exc_info()[1]
2330 pdb.post_mortem(sys.exc_info()[2])
2331 else:
2332 # Note that %r is vital here. '%s' instead can, e.g., cause
2333 # backslashes to get treated as metacharacters on Windows.
2334 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002335
Jim Fultona643b652004-07-14 19:06:50 +00002336def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002337 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002338
2339 Provide the module (or dotted name of the module) containing the
2340 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002341 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002342 """
Tim Peters8485b562004-08-04 18:46:34 +00002343 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002344 testsrc = testsource(module, name)
2345 debug_script(testsrc, pm, module.__dict__)
2346
Tim Peters8485b562004-08-04 18:46:34 +00002347######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002348## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002349######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002350class _TestClass:
2351 """
2352 A pointless class, for sanity-checking of docstring testing.
2353
2354 Methods:
2355 square()
2356 get()
2357
2358 >>> _TestClass(13).get() + _TestClass(-12).get()
2359 1
2360 >>> hex(_TestClass(13).square().get())
2361 '0xa9'
2362 """
2363
2364 def __init__(self, val):
2365 """val -> _TestClass object with associated value val.
2366
2367 >>> t = _TestClass(123)
2368 >>> print t.get()
2369 123
2370 """
2371
2372 self.val = val
2373
2374 def square(self):
2375 """square() -> square TestClass's associated value
2376
2377 >>> _TestClass(13).square().get()
2378 169
2379 """
2380
2381 self.val = self.val ** 2
2382 return self
2383
2384 def get(self):
2385 """get() -> return TestClass's associated value.
2386
2387 >>> x = _TestClass(-42)
2388 >>> print x.get()
2389 -42
2390 """
2391
2392 return self.val
2393
2394__test__ = {"_TestClass": _TestClass,
2395 "string": r"""
2396 Example of a string object, searched as-is.
2397 >>> x = 1; y = 2
2398 >>> x + y, x * y
2399 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002400 """,
2401 "bool-int equivalence": r"""
2402 In 2.2, boolean expressions displayed
2403 0 or 1. By default, we still accept
2404 them. This can be disabled by passing
2405 DONT_ACCEPT_TRUE_FOR_1 to the new
2406 optionflags argument.
2407 >>> 4 == 4
2408 1
2409 >>> 4 == 4
2410 True
2411 >>> 4 > 4
2412 0
2413 >>> 4 > 4
2414 False
2415 """,
Tim Peters8485b562004-08-04 18:46:34 +00002416 "blank lines": r"""
2417 Blank lines can be marked with <BLANKLINE>:
2418 >>> print 'foo\n\nbar\n'
2419 foo
2420 <BLANKLINE>
2421 bar
2422 <BLANKLINE>
2423 """,
2424 }
2425# "ellipsis": r"""
2426# If the ellipsis flag is used, then '...' can be used to
2427# elide substrings in the desired output:
2428# >>> print range(1000)
2429# [0, 1, 2, ..., 999]
2430# """,
2431# "whitespace normalization": r"""
2432# If the whitespace normalization flag is used, then
2433# differences in whitespace are ignored.
2434# >>> print range(30)
2435# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2436# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2437# 27, 28, 29]
2438# """,
2439# }
2440
2441def test1(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002442>>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2443... "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002444>>> from doctest import Tester
2445>>> t = Tester(globs={'x': 42}, verbose=0)
2446>>> t.runstring(r'''
2447... >>> x = x * 2
2448... >>> print x
2449... 42
2450... ''', 'XYZ')
2451**********************************************************************
2452Failure in example: print x
2453from line #2 of XYZ
2454Expected: 42
2455Got: 84
2456(1, 2)
2457>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2458(0, 2)
2459>>> t.summarize()
2460**********************************************************************
24611 items had failures:
2462 1 of 2 in XYZ
2463***Test Failed*** 1 failures.
2464(1, 4)
2465>>> t.summarize(verbose=1)
24661 items passed all tests:
2467 2 tests in example2
2468**********************************************************************
24691 items had failures:
2470 1 of 2 in XYZ
24714 tests in 2 items.
24723 passed and 1 failed.
2473***Test Failed*** 1 failures.
2474(1, 4)
2475"""
2476
2477def test2(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002478 >>> warnings.filterwarnings("ignore", "class Tester",
2479 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002480 >>> t = Tester(globs={}, verbose=1)
2481 >>> test = r'''
2482 ... # just an example
2483 ... >>> x = 1 + 2
2484 ... >>> x
2485 ... 3
2486 ... '''
2487 >>> t.runstring(test, "Example")
2488 Running string Example
2489 Trying: x = 1 + 2
2490 Expecting: nothing
2491 ok
2492 Trying: x
2493 Expecting: 3
2494 ok
2495 0 of 2 examples failed in string Example
2496 (0, 2)
2497"""
2498def test3(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002499 >>> warnings.filterwarnings("ignore", "class Tester",
2500 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002501 >>> t = Tester(globs={}, verbose=0)
2502 >>> def _f():
2503 ... '''Trivial docstring example.
2504 ... >>> assert 2 == 2
2505 ... '''
2506 ... return 32
2507 ...
2508 >>> t.rundoc(_f) # expect 0 failures in 1 example
2509 (0, 1)
2510"""
2511def test4(): """
2512 >>> import new
2513 >>> m1 = new.module('_m1')
2514 >>> m2 = new.module('_m2')
2515 >>> test_data = \"""
2516 ... def _f():
2517 ... '''>>> assert 1 == 1
2518 ... '''
2519 ... def g():
2520 ... '''>>> assert 2 != 1
2521 ... '''
2522 ... class H:
2523 ... '''>>> assert 2 > 1
2524 ... '''
2525 ... def bar(self):
2526 ... '''>>> assert 1 < 2
2527 ... '''
2528 ... \"""
2529 >>> exec test_data in m1.__dict__
2530 >>> exec test_data in m2.__dict__
2531 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2532
2533 Tests that objects outside m1 are excluded:
2534
Tim Peters3ddd60a2004-08-08 02:43:33 +00002535 >>> warnings.filterwarnings("ignore", "class Tester",
2536 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002537 >>> t = Tester(globs={}, verbose=0)
Tim Petersf727c6c2004-08-08 01:48:59 +00002538 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Tim Peters8485b562004-08-04 18:46:34 +00002539 (0, 4)
2540
Tim Petersf727c6c2004-08-08 01:48:59 +00002541 Once more, not excluding stuff outside m1:
Tim Peters8485b562004-08-04 18:46:34 +00002542
2543 >>> t = Tester(globs={}, verbose=0)
2544 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2545 (0, 8)
2546
2547 The exclusion of objects from outside the designated module is
2548 meant to be invoked automagically by testmod.
2549
Tim Petersf727c6c2004-08-08 01:48:59 +00002550 >>> testmod(m1, verbose=False)
2551 (0, 4)
Tim Peters8485b562004-08-04 18:46:34 +00002552"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002553
2554def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002555 #import doctest
2556 #doctest.testmod(doctest, verbose=False,
2557 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2558 # UNIFIED_DIFF)
2559 #print '~'*70
2560 r = unittest.TextTestRunner()
2561 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002562
2563if __name__ == "__main__":
2564 _test()