blob: 6927779ff7a49df16314cfb6da11c57f22cd94ff [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"""
170
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000171__all__ = [
Tim Peters8485b562004-08-04 18:46:34 +0000172 'is_private',
173 'Example',
174 'DocTest',
175 'DocTestFinder',
176 'DocTestRunner',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000177 'testmod',
178 'run_docstring_examples',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000179 'Tester',
Tim Peters19397e52004-08-06 22:02:59 +0000180 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000181 'DocTestSuite',
182 'testsource',
183 'debug',
Tim Peters8485b562004-08-04 18:46:34 +0000184# 'master',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000185]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000186
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000187import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000188
Tim Peters19397e52004-08-06 22:02:59 +0000189import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000190import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000191import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000192from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000193
Jim Fulton356fd192004-08-09 11:34:47 +0000194real_pdb_set_trace = pdb.set_trace
195
Tim Peters19397e52004-08-06 22:02:59 +0000196# There are 4 basic classes:
197# - Example: a <source, want> pair, plus an intra-docstring line number.
198# - DocTest: a collection of examples, parsed from a docstring, plus
199# info about where the docstring came from (name, filename, lineno).
200# - DocTestFinder: extracts DocTests from a given object's docstring and
201# its contained objects' docstrings.
202# - DocTestRunner: runs DocTest cases, and accumulates statistics.
203#
204# So the basic picture is:
205#
206# list of:
207# +------+ +---------+ +-------+
208# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
209# +------+ +---------+ +-------+
210# | Example |
211# | ... |
212# | Example |
213# +---------+
214
Edward Loperac20f572004-08-12 02:02:24 +0000215# Option constants.
216OPTIONFLAGS_BY_NAME = {}
217def register_optionflag(name):
218 flag = 1 << len(OPTIONFLAGS_BY_NAME)
219 OPTIONFLAGS_BY_NAME[name] = flag
220 return flag
221
222DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
223DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
224NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
225ELLIPSIS = register_optionflag('ELLIPSIS')
226UNIFIED_DIFF = register_optionflag('UNIFIED_DIFF')
227CONTEXT_DIFF = register_optionflag('CONTEXT_DIFF')
228
229# Special string markers for use in `want` strings:
230BLANKLINE_MARKER = '<BLANKLINE>'
231ELLIPSIS_MARKER = '...'
232
Tim Peters8485b562004-08-04 18:46:34 +0000233######################################################################
234## Table of Contents
235######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000236# 1. Utility Functions
237# 2. Example & DocTest -- store test cases
238# 3. DocTest Parser -- extracts examples from strings
239# 4. DocTest Finder -- extracts test cases from objects
240# 5. DocTest Runner -- runs test cases
241# 6. Test Functions -- convenient wrappers for testing
242# 7. Tester Class -- for backwards compatibility
243# 8. Unittest Support
244# 9. Debugging Support
245# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000246
Tim Peters8485b562004-08-04 18:46:34 +0000247######################################################################
248## 1. Utility Functions
249######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000250
251def is_private(prefix, base):
252 """prefix, base -> true iff name prefix + "." + base is "private".
253
254 Prefix may be an empty string, and base does not contain a period.
255 Prefix is ignored (although functions you write conforming to this
256 protocol may make use of it).
257 Return true iff base begins with an (at least one) underscore, but
258 does not both begin and end with (at least) two underscores.
259
Tim Petersbafb1fe2004-08-08 01:52:57 +0000260 >>> warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
261 ... "doctest", 0)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000262 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000263 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000264 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000265 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000266 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000267 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000268 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000269 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000270 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000271 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000272 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000273 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000274 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000275 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000276 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000277 warnings.warn("is_private is deprecated; it wasn't useful; "
278 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000279 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000280 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
281
Tim Peters8485b562004-08-04 18:46:34 +0000282def _extract_future_flags(globs):
283 """
284 Return the compiler-flags associated with the future features that
285 have been imported into the given namespace (globs).
286 """
287 flags = 0
288 for fname in __future__.all_feature_names:
289 feature = globs.get(fname, None)
290 if feature is getattr(__future__, fname):
291 flags |= feature.compiler_flag
292 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000293
Tim Peters8485b562004-08-04 18:46:34 +0000294def _normalize_module(module, depth=2):
295 """
296 Return the module specified by `module`. In particular:
297 - If `module` is a module, then return module.
298 - If `module` is a string, then import and return the
299 module with that name.
300 - If `module` is None, then return the calling module.
301 The calling module is assumed to be the module of
302 the stack frame at the given depth in the call stack.
303 """
304 if inspect.ismodule(module):
305 return module
306 elif isinstance(module, (str, unicode)):
307 return __import__(module, globals(), locals(), ["*"])
308 elif module is None:
309 return sys.modules[sys._getframe(depth).f_globals['__name__']]
310 else:
311 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000312
Edward Lopera1ef6112004-08-09 16:14:41 +0000313def _tag_msg(tag, msg, indent=' '):
Tim Peters8485b562004-08-04 18:46:34 +0000314 """
315 Return a string that displays a tag-and-message pair nicely,
316 keeping the tag and its message on the same line when that
Edward Lopera1ef6112004-08-09 16:14:41 +0000317 makes sense. If the message is displayed on separate lines,
318 then `indent` is added to the beginning of each line.
Tim Peters8485b562004-08-04 18:46:34 +0000319 """
Tim Peters8485b562004-08-04 18:46:34 +0000320 # If the message doesn't end in a newline, then add one.
321 if msg[-1:] != '\n':
322 msg += '\n'
323 # If the message is short enough, and contains no internal
324 # newlines, then display it on the same line as the tag.
325 # Otherwise, display the tag on its own line.
326 if (len(tag) + len(msg) < 75 and
327 msg.find('\n', 0, len(msg)-1) == -1):
328 return '%s: %s' % (tag, msg)
329 else:
Edward Lopera1ef6112004-08-09 16:14:41 +0000330 msg = '\n'.join([indent+l for l in msg[:-1].split('\n')])
331 return '%s:\n%s\n' % (tag, msg)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000332
Tim Peters8485b562004-08-04 18:46:34 +0000333# Override some StringIO methods.
334class _SpoofOut(StringIO):
335 def getvalue(self):
336 result = StringIO.getvalue(self)
337 # If anything at all was written, make sure there's a trailing
338 # newline. There's no way for the expected output to indicate
339 # that a trailing newline is missing.
340 if result and not result.endswith("\n"):
341 result += "\n"
342 # Prevent softspace from screwing up the next test case, in
343 # case they used print with a trailing comma in an example.
344 if hasattr(self, "softspace"):
345 del self.softspace
346 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000347
Tim Peters8485b562004-08-04 18:46:34 +0000348 def truncate(self, size=None):
349 StringIO.truncate(self, size)
350 if hasattr(self, "softspace"):
351 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000352
Tim Peters8485b562004-08-04 18:46:34 +0000353######################################################################
354## 2. Example & DocTest
355######################################################################
356## - An "example" is a <source, want> pair, where "source" is a
357## fragment of source code, and "want" is the expected output for
358## "source." The Example class also includes information about
359## where the example was extracted from.
360##
Edward Lopera1ef6112004-08-09 16:14:41 +0000361## - A "doctest" is a collection of examples, typically extracted from
362## a string (such as an object's docstring). The DocTest class also
363## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000364
Tim Peters8485b562004-08-04 18:46:34 +0000365class Example:
366 """
367 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000368 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000369
Edward Loper74bca7a2004-08-12 02:27:44 +0000370 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000371 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000372
Edward Loper74bca7a2004-08-12 02:27:44 +0000373 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000374 from stdout, or a traceback in case of exception). `want` ends
375 with a newline unless it's empty, in which case it's an empty
376 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000377
Edward Loper74bca7a2004-08-12 02:27:44 +0000378 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000379 this Example where the Example begins. This line number is
380 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000381
382 - indent: The example's indentation in the DocTest string.
383 I.e., the number of space characters that preceed the
384 example's first prompt.
385
386 - options: A dictionary mapping from option flags to True or
387 False, which is used to override default options for this
388 example. Any option flags not contained in this dictionary
389 are left at their default value (as specified by the
390 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000391 """
Edward Loper74bca7a2004-08-12 02:27:44 +0000392 def __init__(self, source, want, lineno, indent=0, options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000393 # Normalize inputs.
394 if not source.endswith('\n'):
395 source += '\n'
396 if want and not want.endswith('\n'):
397 want += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000398 # Store properties.
399 self.source = source
400 self.want = want
401 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000402 self.indent = indent
403 if options is None: options = {}
404 self.options = options
Tim Peters8a7d2d52001-01-16 07:10:57 +0000405
Tim Peters8485b562004-08-04 18:46:34 +0000406class DocTest:
407 """
408 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000409 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000410
Tim Peters8485b562004-08-04 18:46:34 +0000411 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000412
Tim Peters8485b562004-08-04 18:46:34 +0000413 - globs: The namespace (aka globals) that the examples should
414 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000415
Tim Peters8485b562004-08-04 18:46:34 +0000416 - name: A name identifying the DocTest (typically, the name of
417 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000418
Tim Peters8485b562004-08-04 18:46:34 +0000419 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000420 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000421
Tim Peters8485b562004-08-04 18:46:34 +0000422 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000423 begins, or `None` if the line number is unavailable. This
424 line number is zero-based, with respect to the beginning of
425 the file.
426
427 - docstring: The string that the examples were extracted from,
428 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000429 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000430 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000431 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000432 Create a new DocTest containing the given examples. The
433 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000434 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000435 assert not isinstance(examples, basestring), \
436 "DocTest no longer accepts str; use DocTestParser instead"
437 self.examples = examples
438 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000439 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000440 self.name = name
441 self.filename = filename
442 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000443
444 def __repr__(self):
445 if len(self.examples) == 0:
446 examples = 'no examples'
447 elif len(self.examples) == 1:
448 examples = '1 example'
449 else:
450 examples = '%d examples' % len(self.examples)
451 return ('<DocTest %s from %s:%s (%s)>' %
452 (self.name, self.filename, self.lineno, examples))
453
454
455 # This lets us sort tests by name:
456 def __cmp__(self, other):
457 if not isinstance(other, DocTest):
458 return -1
459 return cmp((self.name, self.filename, self.lineno, id(self)),
460 (other.name, other.filename, other.lineno, id(other)))
461
462######################################################################
Edward Lopera1ef6112004-08-09 16:14:41 +0000463## 2. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000464######################################################################
465
Edward Lopera1ef6112004-08-09 16:14:41 +0000466class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000467 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000468 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000469 """
Edward Loper7c748462004-08-09 02:06:06 +0000470 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000471 # Source consists of a PS1 line followed by zero or more PS2 lines.
472 (?P<source>
473 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
474 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
475 \n?
476 # Want consists of any non-blank lines that do not start with PS1.
477 (?P<want> (?:(?![ ]*$) # Not a blank line
478 (?![ ]*>>>) # Not a line starting with PS1
479 .*$\n? # But any other line
480 )*)
481 ''', re.MULTILINE | re.VERBOSE)
482 _IS_BLANK_OR_COMMENT = re.compile('^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000483
Edward Lopera1ef6112004-08-09 16:14:41 +0000484 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000485 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000486 Extract all doctest examples from the given string, and
487 collect them into a `DocTest` object.
488
489 `globs`, `name`, `filename`, and `lineno` are attributes for
490 the new `DocTest` object. See the documentation for `DocTest`
491 for more information.
492 """
493 return DocTest(self.get_examples(string, name), globs,
494 name, filename, lineno, string)
495
496 def get_examples(self, string, name='<string>'):
497 """
498 Extract all doctest examples from the given string, and return
499 them as a list of `Example` objects. Line numbers are
500 0-based, because it's most common in doctests that nothing
501 interesting appears on the same line as opening triple-quote,
502 and so the first interesting line is called \"line 1\" then.
503
504 The optional argument `name` is a name identifying this
505 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000506
507 >>> text = '''
508 ... >>> x, y = 2, 3 # no output expected
509 ... >>> if 1:
510 ... ... print x
511 ... ... print y
512 ... 2
513 ... 3
514 ...
515 ... Some text.
516 ... >>> x+y
517 ... 5
518 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000519 >>> for x in DocTestParser().get_examples(text):
Edward Loper78b58f32004-08-09 02:56:02 +0000520 ... print (x.source, x.want, x.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000521 ('x, y = 2, 3 # no output expected\\n', '', 1)
Edward Loper7c748462004-08-09 02:06:06 +0000522 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
Tim Petersbb431472004-08-09 03:51:46 +0000523 ('x+y\\n', '5\\n', 9)
Edward Loper7c748462004-08-09 02:06:06 +0000524 """
525 examples = []
526 charno, lineno = 0, 0
527 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000528 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000529 # Update lineno (lines before this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000530 lineno += string.count('\n', charno, m.start())
Edward Loper7c748462004-08-09 02:06:06 +0000531 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000532 (source, want) = self._parse_example(m, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000533 # Extract extra options from the source.
534 options = self._find_options(source, name, lineno)
535 # If it contains no real source, then ignore it.
Tim Petersd40a92b2004-08-09 03:28:45 +0000536 if self._IS_BLANK_OR_COMMENT(source):
Edward Loper7c748462004-08-09 02:06:06 +0000537 continue
Edward Loper74bca7a2004-08-12 02:27:44 +0000538 # Create an Example, and add it to the list.
539 examples.append( Example(source, want, lineno,
540 len(m.group('indent')), options) )
Edward Loper7c748462004-08-09 02:06:06 +0000541 # Update lineno (lines inside this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000542 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000543 # Update charno.
544 charno = m.end()
545 return examples
546
Edward Lopera1ef6112004-08-09 16:14:41 +0000547 def get_program(self, string, name="<string>"):
Edward Loper7c748462004-08-09 02:06:06 +0000548 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000549 Return an executable program from the given string, as a string.
Edward Loper7c748462004-08-09 02:06:06 +0000550
551 The format of this isn't rigidly defined. In general, doctest
552 examples become the executable statements in the result, and
553 their expected outputs become comments, preceded by an \"#Expected:\"
554 comment. Everything else (text, comments, everything not part of
555 a doctest test) is also placed in comments.
556
Edward Lopera1ef6112004-08-09 16:14:41 +0000557 The optional argument `name` is a name identifying this
558 string, and is only used for error messages.
559
Edward Loper7c748462004-08-09 02:06:06 +0000560 >>> text = '''
561 ... >>> x, y = 2, 3 # no output expected
562 ... >>> if 1:
563 ... ... print x
564 ... ... print y
565 ... 2
566 ... 3
567 ...
568 ... Some text.
569 ... >>> x+y
570 ... 5
571 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000572 >>> print DocTestParser().get_program(text)
Edward Loper7c748462004-08-09 02:06:06 +0000573 x, y = 2, 3 # no output expected
574 if 1:
575 print x
576 print y
577 # Expected:
578 # 2
579 # 3
580 #
581 # Some text.
582 x+y
583 # Expected:
584 # 5
585 """
586 output = []
587 charnum, lineno = 0, 0
588 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000589 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000590 # Add any text before this example, as a comment.
591 if m.start() > charnum:
Edward Lopera1ef6112004-08-09 16:14:41 +0000592 lines = string[charnum:m.start()-1].split('\n')
Edward Loper7c748462004-08-09 02:06:06 +0000593 output.extend([self._comment_line(l) for l in lines])
594 lineno += len(lines)
595
596 # Extract source/want from the regexp match.
Edward Loper74bca7a2004-08-12 02:27:44 +0000597 (source, want) = self._parse_example(m, name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000598 # Display the source
599 output.append(source)
600 # Display the expected output, if any
601 if want:
602 output.append('# Expected:')
603 output.extend(['# '+l for l in want.split('\n')])
604
605 # Update the line number & char number.
Edward Lopera1ef6112004-08-09 16:14:41 +0000606 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000607 charnum = m.end()
608 # Add any remaining text, as comments.
609 output.extend([self._comment_line(l)
Edward Lopera1ef6112004-08-09 16:14:41 +0000610 for l in string[charnum:].split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000611 # Trim junk on both ends.
612 while output and output[-1] == '#':
613 output.pop()
614 while output and output[0] == '#':
615 output.pop(0)
616 # Combine the output, and return it.
617 return '\n'.join(output)
618
Edward Loper74bca7a2004-08-12 02:27:44 +0000619 def _parse_example(self, m, name, lineno):
620 """
621 Given a regular expression match from `_EXAMPLE_RE` (`m`),
622 return a pair `(source, want)`, where `source` is the matched
623 example's source code (with prompts and indentation stripped);
624 and `want` is the example's expected output (with indentation
625 stripped).
626
627 `name` is the string's name, and `lineno` is the line number
628 where the example starts; both are used for error messages.
629 """
Edward Loper7c748462004-08-09 02:06:06 +0000630 # Get the example's indentation level.
631 indent = len(m.group('indent'))
632
633 # Divide source into lines; check that they're properly
634 # indented; and then strip their indentation & prompts.
635 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000636 self._check_prompt_blank(source_lines, indent, name, lineno)
637 self._check_prefix(source_lines[1:], ' '*indent+'.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000638 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000639
640 # Divide want into lines; check that it's properly
641 # indented; and then strip the indentation.
642 want_lines = m.group('want').rstrip().split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000643 self._check_prefix(want_lines, ' '*indent, name,
Edward Loper7c748462004-08-09 02:06:06 +0000644 lineno+len(source_lines))
645 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000646
647 return source, want
648
Edward Loper74bca7a2004-08-12 02:27:44 +0000649 # This regular expression looks for option directives in the
650 # source code of an example. Option directives are comments
651 # starting with "doctest:". Warning: this may give false
652 # positives for string-literals that contain the string
653 # "#doctest:". Eliminating these false positives would require
654 # actually parsing the string; but we limit them by ignoring any
655 # line containing "#doctest:" that is *followed* by a quote mark.
656 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
657 re.MULTILINE)
658
659 def _find_options(self, source, name, lineno):
660 """
661 Return a dictionary containing option overrides extracted from
662 option directives in the given source string.
663
664 `name` is the string's name, and `lineno` is the line number
665 where the example starts; both are used for error messages.
666 """
667 options = {}
668 # (note: with the current regexp, this will match at most once:)
669 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
670 option_strings = m.group(1).replace(',', ' ').split()
671 for option in option_strings:
672 if (option[0] not in '+-' or
673 option[1:] not in OPTIONFLAGS_BY_NAME):
674 raise ValueError('line %r of the doctest for %s '
675 'has an invalid option: %r' %
676 (lineno+1, name, option))
677 flag = OPTIONFLAGS_BY_NAME[option[1:]]
678 options[flag] = (option[0] == '+')
679 if options and self._IS_BLANK_OR_COMMENT(source):
680 raise ValueError('line %r of the doctest for %s has an option '
681 'directive on a line with no example: %r' %
682 (lineno, name, source))
683 return options
684
Edward Loper7c748462004-08-09 02:06:06 +0000685 def _comment_line(self, line):
Edward Loper74bca7a2004-08-12 02:27:44 +0000686 "Return a commented form of the given line"
Edward Loper7c748462004-08-09 02:06:06 +0000687 line = line.rstrip()
Tim Petersdd0e4752004-08-09 03:31:56 +0000688 if line:
689 return '# '+line
690 else:
691 return '#'
Edward Loper7c748462004-08-09 02:06:06 +0000692
Edward Lopera1ef6112004-08-09 16:14:41 +0000693 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000694 """
695 Given the lines of a source string (including prompts and
696 leading indentation), check to make sure that every prompt is
697 followed by a space character. If any line is not followed by
698 a space character, then raise ValueError.
699 """
Edward Loper7c748462004-08-09 02:06:06 +0000700 for i, line in enumerate(lines):
701 if len(line) >= indent+4 and line[indent+3] != ' ':
702 raise ValueError('line %r of the docstring for %s '
703 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000704 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000705 line[indent:indent+3], line))
706
Edward Lopera1ef6112004-08-09 16:14:41 +0000707 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000708 """
709 Check that every line in the given list starts with the given
710 prefix; if any line does not, then raise a ValueError.
711 """
Edward Loper7c748462004-08-09 02:06:06 +0000712 for i, line in enumerate(lines):
713 if line and not line.startswith(prefix):
714 raise ValueError('line %r of the docstring for %s has '
715 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000716 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000717
718
719######################################################################
720## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000721######################################################################
722
723class DocTestFinder:
724 """
725 A class used to extract the DocTests that are relevant to a given
726 object, from its docstring and the docstrings of its contained
727 objects. Doctests can currently be extracted from the following
728 object types: modules, functions, classes, methods, staticmethods,
729 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000730 """
731
Edward Lopera1ef6112004-08-09 16:14:41 +0000732 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000733 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000734 """
735 Create a new doctest finder.
736
Edward Lopera1ef6112004-08-09 16:14:41 +0000737 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000738 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000739 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000740 signature for this factory function should match the signature
741 of the DocTest constructor.
742
Tim Peters8485b562004-08-04 18:46:34 +0000743 If the optional argument `recurse` is false, then `find` will
744 only examine the given object, and not any contained objects.
745 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000746 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000747 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000748 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000749 # _namefilter is undocumented, and exists only for temporary backward-
750 # compatibility support of testmod's deprecated isprivate mess.
751 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000752
753 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000754 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000755 """
756 Return a list of the DocTests that are defined by the given
757 object's docstring, or by any of its contained objects'
758 docstrings.
759
760 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000761 the given object. If the module is not specified or is None, then
762 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000763 correct module. The object's module is used:
764
765 - As a default namespace, if `globs` is not specified.
766 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000767 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000768 - To find the name of the file containing the object.
769 - To help find the line number of the object within its
770 file.
771
Tim Petersf3f57472004-08-08 06:11:48 +0000772 Contained objects whose module does not match `module` are ignored.
773
774 If `module` is False, no attempt to find the module will be made.
775 This is obscure, of use mostly in tests: if `module` is False, or
776 is None but cannot be found automatically, then all objects are
777 considered to belong to the (non-existent) module, so all contained
778 objects will (recursively) be searched for doctests.
779
Tim Peters8485b562004-08-04 18:46:34 +0000780 The globals for each DocTest is formed by combining `globs`
781 and `extraglobs` (bindings in `extraglobs` override bindings
782 in `globs`). A new copy of the globals dictionary is created
783 for each DocTest. If `globs` is not specified, then it
784 defaults to the module's `__dict__`, if specified, or {}
785 otherwise. If `extraglobs` is not specified, then it defaults
786 to {}.
787
Tim Peters8485b562004-08-04 18:46:34 +0000788 """
789 # If name was not specified, then extract it from the object.
790 if name is None:
791 name = getattr(obj, '__name__', None)
792 if name is None:
793 raise ValueError("DocTestFinder.find: name must be given "
794 "when obj.__name__ doesn't exist: %r" %
795 (type(obj),))
796
797 # Find the module that contains the given object (if obj is
798 # a module, then module=obj.). Note: this may fail, in which
799 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000800 if module is False:
801 module = None
802 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000803 module = inspect.getmodule(obj)
804
805 # Read the module's source code. This is used by
806 # DocTestFinder._find_lineno to find the line number for a
807 # given object's docstring.
808 try:
809 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
810 source_lines = linecache.getlines(file)
811 if not source_lines:
812 source_lines = None
813 except TypeError:
814 source_lines = None
815
816 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000817 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000818 if module is None:
819 globs = {}
820 else:
821 globs = module.__dict__.copy()
822 else:
823 globs = globs.copy()
824 if extraglobs is not None:
825 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000826
Tim Peters8485b562004-08-04 18:46:34 +0000827 # Recursively expore `obj`, extracting DocTests.
828 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000829 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000830 return tests
831
832 def _filter(self, obj, prefix, base):
833 """
834 Return true if the given object should not be examined.
835 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000836 return (self._namefilter is not None and
837 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000838
839 def _from_module(self, module, object):
840 """
841 Return true if the given object is defined in the given
842 module.
843 """
844 if module is None:
845 return True
846 elif inspect.isfunction(object):
847 return module.__dict__ is object.func_globals
848 elif inspect.isclass(object):
849 return module.__name__ == object.__module__
850 elif inspect.getmodule(object) is not None:
851 return module is inspect.getmodule(object)
852 elif hasattr(object, '__module__'):
853 return module.__name__ == object.__module__
854 elif isinstance(object, property):
855 return True # [XX] no way not be sure.
856 else:
857 raise ValueError("object must be a class or function")
858
Tim Petersf3f57472004-08-08 06:11:48 +0000859 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000860 """
861 Find tests for the given object and any contained objects, and
862 add them to `tests`.
863 """
864 if self._verbose:
865 print 'Finding tests in %s' % name
866
867 # If we've already processed this object, then ignore it.
868 if id(obj) in seen:
869 return
870 seen[id(obj)] = 1
871
872 # Find a test for this object, and add it to the list of tests.
873 test = self._get_test(obj, name, module, globs, source_lines)
874 if test is not None:
875 tests.append(test)
876
877 # Look for tests in a module's contained objects.
878 if inspect.ismodule(obj) and self._recurse:
879 for valname, val in obj.__dict__.items():
880 # Check if this contained object should be ignored.
881 if self._filter(val, name, valname):
882 continue
883 valname = '%s.%s' % (name, valname)
884 # Recurse to functions & classes.
885 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000886 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000887 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000888 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000889
890 # Look for tests in a module's __test__ dictionary.
891 if inspect.ismodule(obj) and self._recurse:
892 for valname, val in getattr(obj, '__test__', {}).items():
893 if not isinstance(valname, basestring):
894 raise ValueError("DocTestFinder.find: __test__ keys "
895 "must be strings: %r" %
896 (type(valname),))
897 if not (inspect.isfunction(val) or inspect.isclass(val) or
898 inspect.ismethod(val) or inspect.ismodule(val) or
899 isinstance(val, basestring)):
900 raise ValueError("DocTestFinder.find: __test__ values "
901 "must be strings, functions, methods, "
902 "classes, or modules: %r" %
903 (type(val),))
904 valname = '%s.%s' % (name, valname)
905 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000906 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000907
908 # Look for tests in a class's contained objects.
909 if inspect.isclass(obj) and self._recurse:
910 for valname, val in obj.__dict__.items():
911 # Check if this contained object should be ignored.
912 if self._filter(val, name, valname):
913 continue
914 # Special handling for staticmethod/classmethod.
915 if isinstance(val, staticmethod):
916 val = getattr(obj, valname)
917 if isinstance(val, classmethod):
918 val = getattr(obj, valname).im_func
919
920 # Recurse to methods, properties, and nested classes.
921 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +0000922 isinstance(val, property)) and
923 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000924 valname = '%s.%s' % (name, valname)
925 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000926 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000927
928 def _get_test(self, obj, name, module, globs, source_lines):
929 """
930 Return a DocTest for the given object, if it defines a docstring;
931 otherwise, return None.
932 """
933 # Extract the object's docstring. If it doesn't have one,
934 # then return None (no test for this object).
935 if isinstance(obj, basestring):
936 docstring = obj
937 else:
938 try:
939 if obj.__doc__ is None:
940 return None
941 docstring = str(obj.__doc__)
942 except (TypeError, AttributeError):
943 return None
944
945 # Don't bother if the docstring is empty.
946 if not docstring:
947 return None
948
949 # Find the docstring's location in the file.
950 lineno = self._find_lineno(obj, source_lines)
951
952 # Return a DocTest for this object.
953 if module is None:
954 filename = None
955 else:
956 filename = getattr(module, '__file__', module.__name__)
Edward Lopera1ef6112004-08-09 16:14:41 +0000957 return self._parser.get_doctest(docstring, globs, name,
958 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +0000959
960 def _find_lineno(self, obj, source_lines):
961 """
962 Return a line number of the given object's docstring. Note:
963 this method assumes that the object has a docstring.
964 """
965 lineno = None
966
967 # Find the line number for modules.
968 if inspect.ismodule(obj):
969 lineno = 0
970
971 # Find the line number for classes.
972 # Note: this could be fooled if a class is defined multiple
973 # times in a single file.
974 if inspect.isclass(obj):
975 if source_lines is None:
976 return None
977 pat = re.compile(r'^\s*class\s*%s\b' %
978 getattr(obj, '__name__', '-'))
979 for i, line in enumerate(source_lines):
980 if pat.match(line):
981 lineno = i
982 break
983
984 # Find the line number for functions & methods.
985 if inspect.ismethod(obj): obj = obj.im_func
986 if inspect.isfunction(obj): obj = obj.func_code
987 if inspect.istraceback(obj): obj = obj.tb_frame
988 if inspect.isframe(obj): obj = obj.f_code
989 if inspect.iscode(obj):
990 lineno = getattr(obj, 'co_firstlineno', None)-1
991
992 # Find the line number where the docstring starts. Assume
993 # that it's the first line that begins with a quote mark.
994 # Note: this could be fooled by a multiline function
995 # signature, where a continuation line begins with a quote
996 # mark.
997 if lineno is not None:
998 if source_lines is None:
999 return lineno+1
1000 pat = re.compile('(^|.*:)\s*\w*("|\')')
1001 for lineno in range(lineno, len(source_lines)):
1002 if pat.match(source_lines[lineno]):
1003 return lineno
1004
1005 # We couldn't find the line number.
1006 return None
1007
1008######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001009## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001010######################################################################
1011
Tim Peters8485b562004-08-04 18:46:34 +00001012class DocTestRunner:
1013 """
1014 A class used to run DocTest test cases, and accumulate statistics.
1015 The `run` method is used to process a single DocTest case. It
1016 returns a tuple `(f, t)`, where `t` is the number of test cases
1017 tried, and `f` is the number of test cases that failed.
1018
1019 >>> tests = DocTestFinder().find(_TestClass)
1020 >>> runner = DocTestRunner(verbose=False)
1021 >>> for test in tests:
1022 ... print runner.run(test)
1023 (0, 2)
1024 (0, 1)
1025 (0, 2)
1026 (0, 2)
1027
1028 The `summarize` method prints a summary of all the test cases that
1029 have been run by the runner, and returns an aggregated `(f, t)`
1030 tuple:
1031
1032 >>> runner.summarize(verbose=1)
1033 4 items passed all tests:
1034 2 tests in _TestClass
1035 2 tests in _TestClass.__init__
1036 2 tests in _TestClass.get
1037 1 tests in _TestClass.square
1038 7 tests in 4 items.
1039 7 passed and 0 failed.
1040 Test passed.
1041 (0, 7)
1042
1043 The aggregated number of tried examples and failed examples is
1044 also available via the `tries` and `failures` attributes:
1045
1046 >>> runner.tries
1047 7
1048 >>> runner.failures
1049 0
1050
1051 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001052 by an `OutputChecker`. This comparison may be customized with a
1053 number of option flags; see the documentation for `testmod` for
1054 more information. If the option flags are insufficient, then the
1055 comparison may also be customized by passing a subclass of
1056 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001057
1058 The test runner's display output can be controlled in two ways.
1059 First, an output function (`out) can be passed to
1060 `TestRunner.run`; this function will be called with strings that
1061 should be displayed. It defaults to `sys.stdout.write`. If
1062 capturing the output is not sufficient, then the display output
1063 can be also customized by subclassing DocTestRunner, and
1064 overriding the methods `report_start`, `report_success`,
1065 `report_unexpected_exception`, and `report_failure`.
1066 """
1067 # This divider string is used to separate failure messages, and to
1068 # separate sections of the summary.
1069 DIVIDER = "*" * 70
1070
Edward Loper34fcb142004-08-09 02:45:41 +00001071 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001072 """
1073 Create a new test runner.
1074
Edward Loper34fcb142004-08-09 02:45:41 +00001075 Optional keyword arg `checker` is the `OutputChecker` that
1076 should be used to compare the expected outputs and actual
1077 outputs of doctest examples.
1078
Tim Peters8485b562004-08-04 18:46:34 +00001079 Optional keyword arg 'verbose' prints lots of stuff if true,
1080 only failures if false; by default, it's true iff '-v' is in
1081 sys.argv.
1082
1083 Optional argument `optionflags` can be used to control how the
1084 test runner compares expected output to actual output, and how
1085 it displays failures. See the documentation for `testmod` for
1086 more information.
1087 """
Edward Loper34fcb142004-08-09 02:45:41 +00001088 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001089 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001090 verbose = '-v' in sys.argv
1091 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001092 self.optionflags = optionflags
1093
Tim Peters8485b562004-08-04 18:46:34 +00001094 # Keep track of the examples we've run.
1095 self.tries = 0
1096 self.failures = 0
1097 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001098
Tim Peters8485b562004-08-04 18:46:34 +00001099 # Create a fake output target for capturing doctest output.
1100 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001101
Tim Peters8485b562004-08-04 18:46:34 +00001102 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001103 # Reporting methods
1104 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001105
Tim Peters8485b562004-08-04 18:46:34 +00001106 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001107 """
Tim Peters8485b562004-08-04 18:46:34 +00001108 Report that the test runner is about to process the given
1109 example. (Only displays a message if verbose=True)
1110 """
1111 if self._verbose:
1112 out(_tag_msg("Trying", example.source) +
1113 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001114
Tim Peters8485b562004-08-04 18:46:34 +00001115 def report_success(self, out, test, example, got):
1116 """
1117 Report that the given example ran successfully. (Only
1118 displays a message if verbose=True)
1119 """
1120 if self._verbose:
1121 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001122
Tim Peters8485b562004-08-04 18:46:34 +00001123 def report_failure(self, out, test, example, got):
1124 """
1125 Report that the given example failed.
1126 """
1127 # Print an error message.
1128 out(self.__failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001129 self._checker.output_difference(example.want, got,
1130 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001131
Tim Peters8485b562004-08-04 18:46:34 +00001132 def report_unexpected_exception(self, out, test, example, exc_info):
1133 """
1134 Report that the given example raised an unexpected exception.
1135 """
1136 # Get a traceback message.
1137 excout = StringIO()
1138 exc_type, exc_val, exc_tb = exc_info
1139 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
1140 exception_tb = excout.getvalue()
1141 # Print an error message.
1142 out(self.__failure_header(test, example) +
1143 _tag_msg("Exception raised", exception_tb))
Tim Peters7402f792001-10-02 03:53:41 +00001144
Tim Peters8485b562004-08-04 18:46:34 +00001145 def __failure_header(self, test, example):
1146 s = (self.DIVIDER + "\n" +
1147 _tag_msg("Failure in example", example.source))
1148 if test.filename is None:
1149 # [XX] I'm not putting +1 here, to give the same output
1150 # as the old version. But I think it *should* go here.
1151 return s + ("from line #%s of %s\n" %
1152 (example.lineno, test.name))
1153 elif test.lineno is None:
1154 return s + ("from line #%s of %s in %s\n" %
1155 (example.lineno+1, test.name, test.filename))
1156 else:
1157 lineno = test.lineno+example.lineno+1
1158 return s + ("from line #%s of %s (%s)\n" %
1159 (lineno, test.filename, test.name))
Tim Peters7402f792001-10-02 03:53:41 +00001160
Tim Peters8485b562004-08-04 18:46:34 +00001161 #/////////////////////////////////////////////////////////////////
1162 # DocTest Running
1163 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001164
Tim Peters8485b562004-08-04 18:46:34 +00001165 # A regular expression for handling `want` strings that contain
1166 # expected exceptions. It divides `want` into two pieces: the
1167 # pre-exception output (`out`) and the exception message (`exc`),
1168 # as generated by traceback.format_exception_only(). (I assume
1169 # that the exception_only message is the first non-indented line
1170 # starting with word characters after the "Traceback ...".)
1171 _EXCEPTION_RE = re.compile(('^(?P<out>.*)'
1172 '^(?P<hdr>Traceback \((?:%s|%s)\):)\s*$.*?'
1173 '^(?P<exc>\w+.*)') %
1174 ('most recent call last', 'innermost last'),
1175 re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001176
Tim Peters8485b562004-08-04 18:46:34 +00001177 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001178 """
Tim Peters8485b562004-08-04 18:46:34 +00001179 Run the examples in `test`. Write the outcome of each example
1180 with one of the `DocTestRunner.report_*` methods, using the
1181 writer function `out`. `compileflags` is the set of compiler
1182 flags that should be used to execute examples. Return a tuple
1183 `(f, t)`, where `t` is the number of examples tried, and `f`
1184 is the number of examples that failed. The examples are run
1185 in the namespace `test.globs`.
1186 """
1187 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001188 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001189
1190 # Save the option flags (since option directives can be used
1191 # to modify them).
1192 original_optionflags = self.optionflags
1193
1194 # Process each example.
1195 for example in test.examples:
Edward Loper74bca7a2004-08-12 02:27:44 +00001196 # Merge in the example's options.
1197 self.optionflags = original_optionflags
1198 if example.options:
1199 for (optionflag, val) in example.options.items():
1200 if val:
1201 self.optionflags |= optionflag
1202 else:
1203 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001204
1205 # Record that we started this example.
1206 tries += 1
1207 self.report_start(out, test, example)
1208
1209 # Run the example in the given context (globs), and record
1210 # any exception that gets raised. (But don't intercept
1211 # keyboard interrupts.)
1212 try:
Tim Peters208ca702004-08-09 04:12:36 +00001213 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001214 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001215 compileflags, 1) in test.globs
1216 exception = None
1217 except KeyboardInterrupt:
1218 raise
1219 except:
1220 exception = sys.exc_info()
1221
Tim Peters208ca702004-08-09 04:12:36 +00001222 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001223 self._fakeout.truncate(0)
1224
1225 # If the example executed without raising any exceptions,
1226 # then verify its output and report its outcome.
1227 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001228 if self._checker.check_output(example.want, got,
1229 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001230 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001231 else:
Tim Peters8485b562004-08-04 18:46:34 +00001232 self.report_failure(out, test, example, got)
1233 failures += 1
1234
1235 # If the example raised an exception, then check if it was
1236 # expected.
1237 else:
1238 exc_info = sys.exc_info()
1239 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1240
1241 # Search the `want` string for an exception. If we don't
1242 # find one, then report an unexpected exception.
1243 m = self._EXCEPTION_RE.match(example.want)
1244 if m is None:
1245 self.report_unexpected_exception(out, test, example,
1246 exc_info)
1247 failures += 1
1248 else:
1249 exc_hdr = m.group('hdr')+'\n' # Exception header
1250 # The test passes iff the pre-exception output and
1251 # the exception description match the values given
1252 # in `want`.
Edward Loper34fcb142004-08-09 02:45:41 +00001253 if (self._checker.check_output(m.group('out'), got,
1254 self.optionflags) and
1255 self._checker.check_output(m.group('exc'), exc_msg,
1256 self.optionflags)):
Tim Peters8485b562004-08-04 18:46:34 +00001257 # Is +exc_msg the right thing here??
1258 self.report_success(out, test, example,
1259 got+exc_hdr+exc_msg)
1260 else:
1261 self.report_failure(out, test, example,
1262 got+exc_hdr+exc_msg)
1263 failures += 1
1264
1265 # Restore the option flags (in case they were modified)
1266 self.optionflags = original_optionflags
1267
1268 # Record and return the number of failures and tries.
1269 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001270 return failures, tries
1271
Tim Peters8485b562004-08-04 18:46:34 +00001272 def __record_outcome(self, test, f, t):
1273 """
1274 Record the fact that the given DocTest (`test`) generated `f`
1275 failures out of `t` tried examples.
1276 """
1277 f2, t2 = self._name2ft.get(test.name, (0,0))
1278 self._name2ft[test.name] = (f+f2, t+t2)
1279 self.failures += f
1280 self.tries += t
1281
1282 def run(self, test, compileflags=None, out=None, clear_globs=True):
1283 """
1284 Run the examples in `test`, and display the results using the
1285 writer function `out`.
1286
1287 The examples are run in the namespace `test.globs`. If
1288 `clear_globs` is true (the default), then this namespace will
1289 be cleared after the test runs, to help with garbage
1290 collection. If you would like to examine the namespace after
1291 the test completes, then use `clear_globs=False`.
1292
1293 `compileflags` gives the set of flags that should be used by
1294 the Python compiler when running the examples. If not
1295 specified, then it will default to the set of future-import
1296 flags that apply to `globs`.
1297
1298 The output of each example is checked using
1299 `DocTestRunner.check_output`, and the results are formatted by
1300 the `DocTestRunner.report_*` methods.
1301 """
1302 if compileflags is None:
1303 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001304
Tim Peters6c542b72004-08-09 16:43:36 +00001305 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001306 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001307 out = save_stdout.write
1308 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001309
Tim Peters6c542b72004-08-09 16:43:36 +00001310 # Patch pdb.set_trace to restore sys.stdout, so that interactive
1311 # debugging output is visible (not still redirected to self._fakeout).
1312 # Note that we run "the real" pdb.set_trace (captured at doctest
1313 # import time) in our replacement. Because the current run() may
1314 # run another doctest (and so on), the current pdb.set_trace may be
1315 # our set_trace function, which changes sys.stdout. If we called
1316 # a chain of those, we wouldn't be left with the save_stdout
1317 # *this* run() invocation wants.
Jim Fulton356fd192004-08-09 11:34:47 +00001318 def set_trace():
Tim Peters6c542b72004-08-09 16:43:36 +00001319 sys.stdout = save_stdout
Jim Fulton356fd192004-08-09 11:34:47 +00001320 real_pdb_set_trace()
1321
Tim Peters6c542b72004-08-09 16:43:36 +00001322 save_set_trace = pdb.set_trace
1323 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001324 try:
Tim Peters8485b562004-08-04 18:46:34 +00001325 return self.__run(test, compileflags, out)
1326 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001327 sys.stdout = save_stdout
1328 pdb.set_trace = save_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001329 if clear_globs:
1330 test.globs.clear()
1331
1332 #/////////////////////////////////////////////////////////////////
1333 # Summarization
1334 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001335 def summarize(self, verbose=None):
1336 """
Tim Peters8485b562004-08-04 18:46:34 +00001337 Print a summary of all the test cases that have been run by
1338 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1339 the total number of failed examples, and `t` is the total
1340 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001341
Tim Peters8485b562004-08-04 18:46:34 +00001342 The optional `verbose` argument controls how detailed the
1343 summary is. If the verbosity is not specified, then the
1344 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001345 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001346 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001347 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001348 notests = []
1349 passed = []
1350 failed = []
1351 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001352 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001353 name, (f, t) = x
1354 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001355 totalt += t
1356 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001357 if t == 0:
1358 notests.append(name)
1359 elif f == 0:
1360 passed.append( (name, t) )
1361 else:
1362 failed.append(x)
1363 if verbose:
1364 if notests:
1365 print len(notests), "items had no tests:"
1366 notests.sort()
1367 for thing in notests:
1368 print " ", thing
1369 if passed:
1370 print len(passed), "items passed all tests:"
1371 passed.sort()
1372 for thing, count in passed:
1373 print " %3d tests in %s" % (count, thing)
1374 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001375 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001376 print len(failed), "items had failures:"
1377 failed.sort()
1378 for thing, (f, t) in failed:
1379 print " %3d of %3d in %s" % (f, t, thing)
1380 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001381 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001382 print totalt - totalf, "passed and", totalf, "failed."
1383 if totalf:
1384 print "***Test Failed***", totalf, "failures."
1385 elif verbose:
1386 print "Test passed."
1387 return totalf, totalt
1388
Edward Loper34fcb142004-08-09 02:45:41 +00001389class OutputChecker:
1390 """
1391 A class used to check the whether the actual output from a doctest
1392 example matches the expected output. `OutputChecker` defines two
1393 methods: `check_output`, which compares a given pair of outputs,
1394 and returns true if they match; and `output_difference`, which
1395 returns a string describing the differences between two outputs.
1396 """
1397 def check_output(self, want, got, optionflags):
1398 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001399 Return True iff the actual output from an example (`got`)
1400 matches the expected output (`want`). These strings are
1401 always considered to match if they are identical; but
1402 depending on what option flags the test runner is using,
1403 several non-exact match types are also possible. See the
1404 documentation for `TestRunner` for more information about
1405 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001406 """
1407 # Handle the common case first, for efficiency:
1408 # if they're string-identical, always return true.
1409 if got == want:
1410 return True
1411
1412 # The values True and False replaced 1 and 0 as the return
1413 # value for boolean comparisons in Python 2.3.
1414 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1415 if (got,want) == ("True\n", "1\n"):
1416 return True
1417 if (got,want) == ("False\n", "0\n"):
1418 return True
1419
1420 # <BLANKLINE> can be used as a special sequence to signify a
1421 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1422 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1423 # Replace <BLANKLINE> in want with a blank line.
1424 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1425 '', want)
1426 # If a line in got contains only spaces, then remove the
1427 # spaces.
1428 got = re.sub('(?m)^\s*?$', '', got)
1429 if got == want:
1430 return True
1431
1432 # This flag causes doctest to ignore any differences in the
1433 # contents of whitespace strings. Note that this can be used
1434 # in conjunction with the ELLISPIS flag.
1435 if (optionflags & NORMALIZE_WHITESPACE):
1436 got = ' '.join(got.split())
1437 want = ' '.join(want.split())
1438 if got == want:
1439 return True
1440
1441 # The ELLIPSIS flag says to let the sequence "..." in `want`
1442 # match any substring in `got`. We implement this by
1443 # transforming `want` into a regular expression.
1444 if (optionflags & ELLIPSIS):
1445 # Escape any special regexp characters
1446 want_re = re.escape(want)
1447 # Replace ellipsis markers ('...') with .*
1448 want_re = want_re.replace(re.escape(ELLIPSIS_MARKER), '.*')
1449 # Require that it matches the entire string; and set the
1450 # re.DOTALL flag (with '(?s)').
1451 want_re = '(?s)^%s$' % want_re
1452 # Check if the `want_re` regexp matches got.
1453 if re.match(want_re, got):
1454 return True
1455
1456 # We didn't find any match; return false.
1457 return False
1458
1459 def output_difference(self, want, got, optionflags):
1460 """
1461 Return a string describing the differences between the
Edward Loper74bca7a2004-08-12 02:27:44 +00001462 expected output for an example (`want`) and the actual output
1463 (`got`). `optionflags` is the set of option flags used to
1464 compare `want` and `got`. `indent` is the indentation of the
1465 original example.
Edward Loper34fcb142004-08-09 02:45:41 +00001466 """
1467 # If <BLANKLINE>s are being used, then replace <BLANKLINE>
1468 # with blank lines in the expected output string.
1469 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1470 want = re.sub('(?m)^%s$' % re.escape(BLANKLINE_MARKER), '', want)
1471
1472 # Check if we should use diff. Don't use diff if the actual
1473 # or expected outputs are too short, or if the expected output
1474 # contains an ellipsis marker.
1475 if ((optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and
1476 want.count('\n') > 2 and got.count('\n') > 2 and
1477 not (optionflags & ELLIPSIS and '...' in want)):
1478 # Split want & got into lines.
1479 want_lines = [l+'\n' for l in want.split('\n')]
1480 got_lines = [l+'\n' for l in got.split('\n')]
1481 # Use difflib to find their differences.
1482 if optionflags & UNIFIED_DIFF:
1483 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1484 fromfile='Expected', tofile='Got')
1485 kind = 'unified'
1486 elif optionflags & CONTEXT_DIFF:
1487 diff = difflib.context_diff(want_lines, got_lines, n=2,
1488 fromfile='Expected', tofile='Got')
1489 kind = 'context'
1490 else:
1491 assert 0, 'Bad diff option'
1492 # Remove trailing whitespace on diff output.
1493 diff = [line.rstrip() + '\n' for line in diff]
1494 return _tag_msg("Differences (" + kind + " diff)",
1495 ''.join(diff))
1496
1497 # If we're not using diff, then simply list the expected
1498 # output followed by the actual output.
1499 return (_tag_msg("Expected", want or "Nothing") +
1500 _tag_msg("Got", got))
1501
Tim Peters19397e52004-08-06 22:02:59 +00001502class DocTestFailure(Exception):
1503 """A DocTest example has failed in debugging mode.
1504
1505 The exception instance has variables:
1506
1507 - test: the DocTest object being run
1508
1509 - excample: the Example object that failed
1510
1511 - got: the actual output
1512 """
1513 def __init__(self, test, example, got):
1514 self.test = test
1515 self.example = example
1516 self.got = got
1517
1518 def __str__(self):
1519 return str(self.test)
1520
1521class UnexpectedException(Exception):
1522 """A DocTest example has encountered an unexpected exception
1523
1524 The exception instance has variables:
1525
1526 - test: the DocTest object being run
1527
1528 - excample: the Example object that failed
1529
1530 - exc_info: the exception info
1531 """
1532 def __init__(self, test, example, exc_info):
1533 self.test = test
1534 self.example = example
1535 self.exc_info = exc_info
1536
1537 def __str__(self):
1538 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001539
Tim Peters19397e52004-08-06 22:02:59 +00001540class DebugRunner(DocTestRunner):
1541 r"""Run doc tests but raise an exception as soon as there is a failure.
1542
1543 If an unexpected exception occurs, an UnexpectedException is raised.
1544 It contains the test, the example, and the original exception:
1545
1546 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001547 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1548 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001549 >>> try:
1550 ... runner.run(test)
1551 ... except UnexpectedException, failure:
1552 ... pass
1553
1554 >>> failure.test is test
1555 True
1556
1557 >>> failure.example.want
1558 '42\n'
1559
1560 >>> exc_info = failure.exc_info
1561 >>> raise exc_info[0], exc_info[1], exc_info[2]
1562 Traceback (most recent call last):
1563 ...
1564 KeyError
1565
1566 We wrap the original exception to give the calling application
1567 access to the test and example information.
1568
1569 If the output doesn't match, then a DocTestFailure is raised:
1570
Edward Lopera1ef6112004-08-09 16:14:41 +00001571 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001572 ... >>> x = 1
1573 ... >>> x
1574 ... 2
1575 ... ''', {}, 'foo', 'foo.py', 0)
1576
1577 >>> try:
1578 ... runner.run(test)
1579 ... except DocTestFailure, failure:
1580 ... pass
1581
1582 DocTestFailure objects provide access to the test:
1583
1584 >>> failure.test is test
1585 True
1586
1587 As well as to the example:
1588
1589 >>> failure.example.want
1590 '2\n'
1591
1592 and the actual output:
1593
1594 >>> failure.got
1595 '1\n'
1596
1597 If a failure or error occurs, the globals are left intact:
1598
1599 >>> del test.globs['__builtins__']
1600 >>> test.globs
1601 {'x': 1}
1602
Edward Lopera1ef6112004-08-09 16:14:41 +00001603 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001604 ... >>> x = 2
1605 ... >>> raise KeyError
1606 ... ''', {}, 'foo', 'foo.py', 0)
1607
1608 >>> runner.run(test)
1609 Traceback (most recent call last):
1610 ...
1611 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001612
Tim Peters19397e52004-08-06 22:02:59 +00001613 >>> del test.globs['__builtins__']
1614 >>> test.globs
1615 {'x': 2}
1616
1617 But the globals are cleared if there is no error:
1618
Edward Lopera1ef6112004-08-09 16:14:41 +00001619 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001620 ... >>> x = 2
1621 ... ''', {}, 'foo', 'foo.py', 0)
1622
1623 >>> runner.run(test)
1624 (0, 1)
1625
1626 >>> test.globs
1627 {}
1628
1629 """
1630
1631 def run(self, test, compileflags=None, out=None, clear_globs=True):
1632 r = DocTestRunner.run(self, test, compileflags, out, False)
1633 if clear_globs:
1634 test.globs.clear()
1635 return r
1636
1637 def report_unexpected_exception(self, out, test, example, exc_info):
1638 raise UnexpectedException(test, example, exc_info)
1639
1640 def report_failure(self, out, test, example, got):
1641 raise DocTestFailure(test, example, got)
1642
Tim Peters8485b562004-08-04 18:46:34 +00001643######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001644## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001645######################################################################
1646# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001647
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001648def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001649 report=True, optionflags=0, extraglobs=None,
1650 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001651 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001652 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001653
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001654 Test examples in docstrings in functions and classes reachable
1655 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001656 with m.__doc__. Unless isprivate is specified, private names
1657 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001658
1659 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001660 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001661 function and class docstrings are tested even if the name is private;
1662 strings are tested directly, as if they were docstrings.
1663
1664 Return (#failures, #tests).
1665
1666 See doctest.__doc__ for an overview.
1667
1668 Optional keyword arg "name" gives the name of the module; by default
1669 use m.__name__.
1670
1671 Optional keyword arg "globs" gives a dict to be used as the globals
1672 when executing examples; by default, use m.__dict__. A copy of this
1673 dict is actually used for each docstring, so that each docstring's
1674 examples start with a clean slate.
1675
Tim Peters8485b562004-08-04 18:46:34 +00001676 Optional keyword arg "extraglobs" gives a dictionary that should be
1677 merged into the globals that are used to execute examples. By
1678 default, no extra globals are used. This is new in 2.4.
1679
Tim Peters8a7d2d52001-01-16 07:10:57 +00001680 Optional keyword arg "verbose" prints lots of stuff if true, prints
1681 only failures if false; by default, it's true iff "-v" is in sys.argv.
1682
Tim Peters8a7d2d52001-01-16 07:10:57 +00001683 Optional keyword arg "report" prints a summary at the end when true,
1684 else prints nothing at the end. In verbose mode, the summary is
1685 detailed, else very brief (in fact, empty if all tests passed).
1686
Tim Peters6ebe61f2003-06-27 20:48:05 +00001687 Optional keyword arg "optionflags" or's together module constants,
1688 and defaults to 0. This is new in 2.3. Possible values:
1689
1690 DONT_ACCEPT_TRUE_FOR_1
1691 By default, if an expected output block contains just "1",
1692 an actual output block containing just "True" is considered
1693 to be a match, and similarly for "0" versus "False". When
1694 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1695 is allowed.
1696
Tim Peters8485b562004-08-04 18:46:34 +00001697 DONT_ACCEPT_BLANKLINE
1698 By default, if an expected output block contains a line
1699 containing only the string "<BLANKLINE>", then that line
1700 will match a blank line in the actual output. When
1701 DONT_ACCEPT_BLANKLINE is specified, this substitution is
1702 not allowed.
1703
1704 NORMALIZE_WHITESPACE
1705 When NORMALIZE_WHITESPACE is specified, all sequences of
1706 whitespace are treated as equal. I.e., any sequence of
1707 whitespace within the expected output will match any
1708 sequence of whitespace within the actual output.
1709
1710 ELLIPSIS
1711 When ELLIPSIS is specified, then an ellipsis marker
1712 ("...") in the expected output can match any substring in
1713 the actual output.
1714
1715 UNIFIED_DIFF
1716 When UNIFIED_DIFF is specified, failures that involve
1717 multi-line expected and actual outputs will be displayed
1718 using a unified diff.
1719
1720 CONTEXT_DIFF
1721 When CONTEXT_DIFF is specified, failures that involve
1722 multi-line expected and actual outputs will be displayed
1723 using a context diff.
Tim Peters19397e52004-08-06 22:02:59 +00001724
1725 Optional keyword arg "raise_on_error" raises an exception on the
1726 first unexpected exception or failure. This allows failures to be
1727 post-mortem debugged.
1728
Tim Petersf727c6c2004-08-08 01:48:59 +00001729 Deprecated in Python 2.4:
1730 Optional keyword arg "isprivate" specifies a function used to
1731 determine whether a name is private. The default function is
1732 treat all functions as public. Optionally, "isprivate" can be
1733 set to doctest.is_private to skip over functions marked as private
1734 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001735 """
1736
1737 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001738 Advanced tomfoolery: testmod runs methods of a local instance of
1739 class doctest.Tester, then merges the results into (or creates)
1740 global Tester instance doctest.master. Methods of doctest.master
1741 can be called directly too, if you want to do something unusual.
1742 Passing report=0 to testmod is especially useful then, to delay
1743 displaying a summary. Invoke doctest.master.summarize(verbose)
1744 when you're done fiddling.
1745 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001746 if isprivate is not None:
1747 warnings.warn("the isprivate argument is deprecated; "
1748 "examine DocTestFinder.find() lists instead",
1749 DeprecationWarning)
1750
Tim Peters8485b562004-08-04 18:46:34 +00001751 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001752 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001753 # DWA - m will still be None if this wasn't invoked from the command
1754 # line, in which case the following TypeError is about as good an error
1755 # as we should expect
1756 m = sys.modules.get('__main__')
1757
Tim Peters8485b562004-08-04 18:46:34 +00001758 # Check that we were actually given a module.
1759 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001760 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001761
1762 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001763 if name is None:
1764 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001765
1766 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001767 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001768
1769 if raise_on_error:
1770 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1771 else:
1772 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1773
Tim Peters8485b562004-08-04 18:46:34 +00001774 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1775 runner.run(test)
1776
Tim Peters8a7d2d52001-01-16 07:10:57 +00001777 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001778 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001779
Tim Peters8485b562004-08-04 18:46:34 +00001780 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001781
Tim Peters8485b562004-08-04 18:46:34 +00001782def run_docstring_examples(f, globs, verbose=False, name="NoName",
1783 compileflags=None, optionflags=0):
1784 """
1785 Test examples in the given object's docstring (`f`), using `globs`
1786 as globals. Optional argument `name` is used in failure messages.
1787 If the optional argument `verbose` is true, then generate output
1788 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001789
Tim Peters8485b562004-08-04 18:46:34 +00001790 `compileflags` gives the set of flags that should be used by the
1791 Python compiler when running the examples. If not specified, then
1792 it will default to the set of future-import flags that apply to
1793 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001794
Tim Peters8485b562004-08-04 18:46:34 +00001795 Optional keyword arg `optionflags` specifies options for the
1796 testing and output. See the documentation for `testmod` for more
1797 information.
1798 """
1799 # Find, parse, and run all tests in the given module.
1800 finder = DocTestFinder(verbose=verbose, recurse=False)
1801 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1802 for test in finder.find(f, name, globs=globs):
1803 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001804
Tim Peters8485b562004-08-04 18:46:34 +00001805######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001806## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001807######################################################################
1808# This is provided only for backwards compatibility. It's not
1809# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001810
Tim Peters8485b562004-08-04 18:46:34 +00001811class Tester:
1812 def __init__(self, mod=None, globs=None, verbose=None,
1813 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001814
1815 warnings.warn("class Tester is deprecated; "
1816 "use class doctest.DocTestRunner instead",
1817 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001818 if mod is None and globs is None:
1819 raise TypeError("Tester.__init__: must specify mod or globs")
1820 if mod is not None and not _ismodule(mod):
1821 raise TypeError("Tester.__init__: mod must be a module; %r" %
1822 (mod,))
1823 if globs is None:
1824 globs = mod.__dict__
1825 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001826
Tim Peters8485b562004-08-04 18:46:34 +00001827 self.verbose = verbose
1828 self.isprivate = isprivate
1829 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001830 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001831 self.testrunner = DocTestRunner(verbose=verbose,
1832 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001833
Tim Peters8485b562004-08-04 18:46:34 +00001834 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001835 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001836 if self.verbose:
1837 print "Running string", name
1838 (f,t) = self.testrunner.run(test)
1839 if self.verbose:
1840 print f, "of", t, "examples failed in string", name
1841 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001842
Tim Petersf3f57472004-08-08 06:11:48 +00001843 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001844 f = t = 0
1845 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001846 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001847 for test in tests:
1848 (f2, t2) = self.testrunner.run(test)
1849 (f,t) = (f+f2, t+t2)
1850 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001851
Tim Peters8485b562004-08-04 18:46:34 +00001852 def rundict(self, d, name, module=None):
1853 import new
1854 m = new.module(name)
1855 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001856 if module is None:
1857 module = False
1858 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001859
Tim Peters8485b562004-08-04 18:46:34 +00001860 def run__test__(self, d, name):
1861 import new
1862 m = new.module(name)
1863 m.__test__ = d
1864 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001865
Tim Peters8485b562004-08-04 18:46:34 +00001866 def summarize(self, verbose=None):
1867 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001868
Tim Peters8485b562004-08-04 18:46:34 +00001869 def merge(self, other):
1870 d = self.testrunner._name2ft
1871 for name, (f, t) in other.testrunner._name2ft.items():
1872 if name in d:
1873 print "*** Tester.merge: '" + name + "' in both" \
1874 " testers; summing outcomes."
1875 f2, t2 = d[name]
1876 f = f + f2
1877 t = t + t2
1878 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001879
Tim Peters8485b562004-08-04 18:46:34 +00001880######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001881## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001882######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001883
Tim Peters19397e52004-08-06 22:02:59 +00001884class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001885
Edward Loper34fcb142004-08-09 02:45:41 +00001886 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
1887 checker=None):
Jim Fultona643b652004-07-14 19:06:50 +00001888 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00001889 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00001890 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00001891 self._dt_test = test
1892 self._dt_setUp = setUp
1893 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00001894
Jim Fultona643b652004-07-14 19:06:50 +00001895 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00001896 if self._dt_setUp is not None:
1897 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00001898
1899 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00001900 if self._dt_tearDown is not None:
1901 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00001902
1903 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00001904 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00001905 old = sys.stdout
1906 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00001907 runner = DocTestRunner(optionflags=self._dt_optionflags,
1908 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001909
Jim Fultona643b652004-07-14 19:06:50 +00001910 try:
Tim Peters19397e52004-08-06 22:02:59 +00001911 runner.DIVIDER = "-"*70
1912 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00001913 finally:
1914 sys.stdout = old
1915
1916 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00001917 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00001918
Tim Peters19397e52004-08-06 22:02:59 +00001919 def format_failure(self, err):
1920 test = self._dt_test
1921 if test.lineno is None:
1922 lineno = 'unknown line number'
1923 else:
1924 lineno = 'line %s' % test.lineno
1925 lname = '.'.join(test.name.split('.')[-1:])
1926 return ('Failed doctest test for %s\n'
1927 ' File "%s", line %s, in %s\n\n%s'
1928 % (test.name, test.filename, lineno, lname, err)
1929 )
1930
1931 def debug(self):
1932 r"""Run the test case without results and without catching exceptions
1933
1934 The unit test framework includes a debug method on test cases
1935 and test suites to support post-mortem debugging. The test code
1936 is run in such a way that errors are not caught. This way a
1937 caller can catch the errors and initiate post-mortem debugging.
1938
1939 The DocTestCase provides a debug method that raises
1940 UnexpectedException errors if there is an unexepcted
1941 exception:
1942
Edward Lopera1ef6112004-08-09 16:14:41 +00001943 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00001944 ... {}, 'foo', 'foo.py', 0)
1945 >>> case = DocTestCase(test)
1946 >>> try:
1947 ... case.debug()
1948 ... except UnexpectedException, failure:
1949 ... pass
1950
1951 The UnexpectedException contains the test, the example, and
1952 the original exception:
1953
1954 >>> failure.test is test
1955 True
1956
1957 >>> failure.example.want
1958 '42\n'
1959
1960 >>> exc_info = failure.exc_info
1961 >>> raise exc_info[0], exc_info[1], exc_info[2]
1962 Traceback (most recent call last):
1963 ...
1964 KeyError
1965
1966 If the output doesn't match, then a DocTestFailure is raised:
1967
Edward Lopera1ef6112004-08-09 16:14:41 +00001968 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001969 ... >>> x = 1
1970 ... >>> x
1971 ... 2
1972 ... ''', {}, 'foo', 'foo.py', 0)
1973 >>> case = DocTestCase(test)
1974
1975 >>> try:
1976 ... case.debug()
1977 ... except DocTestFailure, failure:
1978 ... pass
1979
1980 DocTestFailure objects provide access to the test:
1981
1982 >>> failure.test is test
1983 True
1984
1985 As well as to the example:
1986
1987 >>> failure.example.want
1988 '2\n'
1989
1990 and the actual output:
1991
1992 >>> failure.got
1993 '1\n'
1994
1995 """
1996
Edward Loper34fcb142004-08-09 02:45:41 +00001997 runner = DebugRunner(optionflags=self._dt_optionflags,
1998 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001999 runner.run(self._dt_test, out=nooutput)
Jim Fultona643b652004-07-14 19:06:50 +00002000
2001 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002002 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002003
2004 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002005 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002006 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2007
2008 __str__ = __repr__
2009
2010 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002011 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002012
Tim Peters19397e52004-08-06 22:02:59 +00002013def nooutput(*args):
2014 pass
Jim Fultona643b652004-07-14 19:06:50 +00002015
Tim Peters19397e52004-08-06 22:02:59 +00002016def DocTestSuite(module=None, globs=None, extraglobs=None,
2017 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002018 setUp=lambda: None, tearDown=lambda: None,
2019 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002020 """
Tim Peters19397e52004-08-06 22:02:59 +00002021 Convert doctest tests for a mudule to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002022
Tim Peters19397e52004-08-06 22:02:59 +00002023 This converts each documentation string in a module that
2024 contains doctest tests to a unittest test case. If any of the
2025 tests in a doc string fail, then the test case fails. An exception
2026 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002027 (sometimes approximate) line number.
2028
Tim Peters19397e52004-08-06 22:02:59 +00002029 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002030 can be either a module or a module name.
2031
2032 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002033 """
Jim Fultona643b652004-07-14 19:06:50 +00002034
Tim Peters8485b562004-08-04 18:46:34 +00002035 if test_finder is None:
2036 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002037
Tim Peters19397e52004-08-06 22:02:59 +00002038 module = _normalize_module(module)
2039 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2040 if globs is None:
2041 globs = module.__dict__
2042 if not tests: # [XX] why do we want to do this?
2043 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002044
2045 tests.sort()
2046 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002047 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002048 if len(test.examples) == 0:
2049 continue
Tim Peters8485b562004-08-04 18:46:34 +00002050 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002051 filename = module.__file__
2052 if filename.endswith(".pyc"):
2053 filename = filename[:-1]
2054 elif filename.endswith(".pyo"):
2055 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002056 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002057 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2058 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002059
2060 return suite
2061
2062class DocFileCase(DocTestCase):
2063
2064 def id(self):
2065 return '_'.join(self._dt_test.name.split('.'))
2066
2067 def __repr__(self):
2068 return self._dt_test.filename
2069 __str__ = __repr__
2070
2071 def format_failure(self, err):
2072 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2073 % (self._dt_test.name, self._dt_test.filename, err)
2074 )
2075
2076def DocFileTest(path, package=None, globs=None,
2077 setUp=None, tearDown=None,
2078 optionflags=0):
2079 package = _normalize_module(package)
2080 name = path.split('/')[-1]
2081 dir = os.path.split(package.__file__)[0]
2082 path = os.path.join(dir, *(path.split('/')))
2083 doc = open(path).read()
2084
2085 if globs is None:
2086 globs = {}
2087
Edward Lopera1ef6112004-08-09 16:14:41 +00002088 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002089
2090 return DocFileCase(test, optionflags, setUp, tearDown)
2091
2092def DocFileSuite(*paths, **kw):
2093 """Creates a suite of doctest files.
2094
2095 One or more text file paths are given as strings. These should
2096 use "/" characters to separate path segments. Paths are relative
2097 to the directory of the calling module, or relative to the package
2098 passed as a keyword argument.
2099
2100 A number of options may be provided as keyword arguments:
2101
2102 package
2103 The name of a Python package. Text-file paths will be
2104 interpreted relative to the directory containing this package.
2105 The package may be supplied as a package object or as a dotted
2106 package name.
2107
2108 setUp
2109 The name of a set-up function. This is called before running the
2110 tests in each file.
2111
2112 tearDown
2113 The name of a tear-down function. This is called after running the
2114 tests in each file.
2115
2116 globs
2117 A dictionary containing initial global variables for the tests.
2118 """
2119 suite = unittest.TestSuite()
2120
2121 # We do this here so that _normalize_module is called at the right
2122 # level. If it were called in DocFileTest, then this function
2123 # would be the caller and we might guess the package incorrectly.
2124 kw['package'] = _normalize_module(kw.get('package'))
2125
2126 for path in paths:
2127 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002128
Tim Petersdb3756d2003-06-29 05:30:48 +00002129 return suite
2130
Tim Peters8485b562004-08-04 18:46:34 +00002131######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002132## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002133######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002134
Tim Peters19397e52004-08-06 22:02:59 +00002135def script_from_examples(s):
2136 r"""Extract script from text with examples.
2137
2138 Converts text with examples to a Python script. Example input is
2139 converted to regular code. Example output and all other words
2140 are converted to comments:
2141
2142 >>> text = '''
2143 ... Here are examples of simple math.
2144 ...
2145 ... Python has super accurate integer addition
2146 ...
2147 ... >>> 2 + 2
2148 ... 5
2149 ...
2150 ... And very friendly error messages:
2151 ...
2152 ... >>> 1/0
2153 ... To Infinity
2154 ... And
2155 ... Beyond
2156 ...
2157 ... You can use logic if you want:
2158 ...
2159 ... >>> if 0:
2160 ... ... blah
2161 ... ... blah
2162 ... ...
2163 ...
2164 ... Ho hum
2165 ... '''
2166
2167 >>> print script_from_examples(text)
2168 # Here are examples of simple math.
2169 #
2170 # Python has super accurate integer addition
2171 #
2172 2 + 2
2173 # Expected:
2174 # 5
2175 #
2176 # And very friendly error messages:
2177 #
2178 1/0
2179 # Expected:
2180 # To Infinity
2181 # And
2182 # Beyond
2183 #
2184 # You can use logic if you want:
2185 #
2186 if 0:
2187 blah
2188 blah
2189 <BLANKLINE>
2190 #
2191 # Ho hum
2192 """
2193
Edward Lopera1ef6112004-08-09 16:14:41 +00002194 return DocTestParser().get_program(s)
Tim Peters19397e52004-08-06 22:02:59 +00002195
Tim Peters8485b562004-08-04 18:46:34 +00002196def _want_comment(example):
2197 """
Tim Peters19397e52004-08-06 22:02:59 +00002198 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002199 """
Jim Fultona643b652004-07-14 19:06:50 +00002200 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002201 want = example.want
2202 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002203 if want[-1] == '\n':
2204 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002205 want = "\n# ".join(want.split("\n"))
2206 want = "\n# Expected:\n# %s" % want
2207 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002208
2209def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002210 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002211
2212 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002213 test to be debugged and the name (within the module) of the object
2214 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002215 """
Tim Peters8485b562004-08-04 18:46:34 +00002216 module = _normalize_module(module)
2217 tests = DocTestFinder().find(module)
2218 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002219 if not test:
2220 raise ValueError(name, "not found in tests")
2221 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002222 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002223 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002224
Jim Fultona643b652004-07-14 19:06:50 +00002225def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002226 """Debug a single doctest docstring, in argument `src`'"""
2227 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002228 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002229
Jim Fultona643b652004-07-14 19:06:50 +00002230def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002231 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002232 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002233
Tim Petersdb3756d2003-06-29 05:30:48 +00002234 srcfilename = tempfile.mktemp("doctestdebug.py")
Tim Peters8485b562004-08-04 18:46:34 +00002235 f = open(srcfilename, 'w')
2236 f.write(src)
2237 f.close()
2238
Jim Fultona643b652004-07-14 19:06:50 +00002239 if globs:
2240 globs = globs.copy()
2241 else:
2242 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002243
Tim Peters8485b562004-08-04 18:46:34 +00002244 if pm:
2245 try:
2246 execfile(srcfilename, globs, globs)
2247 except:
2248 print sys.exc_info()[1]
2249 pdb.post_mortem(sys.exc_info()[2])
2250 else:
2251 # Note that %r is vital here. '%s' instead can, e.g., cause
2252 # backslashes to get treated as metacharacters on Windows.
2253 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002254
Jim Fultona643b652004-07-14 19:06:50 +00002255def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002256 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002257
2258 Provide the module (or dotted name of the module) containing the
2259 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002260 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002261 """
Tim Peters8485b562004-08-04 18:46:34 +00002262 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002263 testsrc = testsource(module, name)
2264 debug_script(testsrc, pm, module.__dict__)
2265
Tim Peters8485b562004-08-04 18:46:34 +00002266######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002267## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002268######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002269class _TestClass:
2270 """
2271 A pointless class, for sanity-checking of docstring testing.
2272
2273 Methods:
2274 square()
2275 get()
2276
2277 >>> _TestClass(13).get() + _TestClass(-12).get()
2278 1
2279 >>> hex(_TestClass(13).square().get())
2280 '0xa9'
2281 """
2282
2283 def __init__(self, val):
2284 """val -> _TestClass object with associated value val.
2285
2286 >>> t = _TestClass(123)
2287 >>> print t.get()
2288 123
2289 """
2290
2291 self.val = val
2292
2293 def square(self):
2294 """square() -> square TestClass's associated value
2295
2296 >>> _TestClass(13).square().get()
2297 169
2298 """
2299
2300 self.val = self.val ** 2
2301 return self
2302
2303 def get(self):
2304 """get() -> return TestClass's associated value.
2305
2306 >>> x = _TestClass(-42)
2307 >>> print x.get()
2308 -42
2309 """
2310
2311 return self.val
2312
2313__test__ = {"_TestClass": _TestClass,
2314 "string": r"""
2315 Example of a string object, searched as-is.
2316 >>> x = 1; y = 2
2317 >>> x + y, x * y
2318 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002319 """,
2320 "bool-int equivalence": r"""
2321 In 2.2, boolean expressions displayed
2322 0 or 1. By default, we still accept
2323 them. This can be disabled by passing
2324 DONT_ACCEPT_TRUE_FOR_1 to the new
2325 optionflags argument.
2326 >>> 4 == 4
2327 1
2328 >>> 4 == 4
2329 True
2330 >>> 4 > 4
2331 0
2332 >>> 4 > 4
2333 False
2334 """,
Tim Peters8485b562004-08-04 18:46:34 +00002335 "blank lines": r"""
2336 Blank lines can be marked with <BLANKLINE>:
2337 >>> print 'foo\n\nbar\n'
2338 foo
2339 <BLANKLINE>
2340 bar
2341 <BLANKLINE>
2342 """,
2343 }
2344# "ellipsis": r"""
2345# If the ellipsis flag is used, then '...' can be used to
2346# elide substrings in the desired output:
2347# >>> print range(1000)
2348# [0, 1, 2, ..., 999]
2349# """,
2350# "whitespace normalization": r"""
2351# If the whitespace normalization flag is used, then
2352# differences in whitespace are ignored.
2353# >>> print range(30)
2354# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2355# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2356# 27, 28, 29]
2357# """,
2358# }
2359
2360def test1(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002361>>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2362... "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002363>>> from doctest import Tester
2364>>> t = Tester(globs={'x': 42}, verbose=0)
2365>>> t.runstring(r'''
2366... >>> x = x * 2
2367... >>> print x
2368... 42
2369... ''', 'XYZ')
2370**********************************************************************
2371Failure in example: print x
2372from line #2 of XYZ
2373Expected: 42
2374Got: 84
2375(1, 2)
2376>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2377(0, 2)
2378>>> t.summarize()
2379**********************************************************************
23801 items had failures:
2381 1 of 2 in XYZ
2382***Test Failed*** 1 failures.
2383(1, 4)
2384>>> t.summarize(verbose=1)
23851 items passed all tests:
2386 2 tests in example2
2387**********************************************************************
23881 items had failures:
2389 1 of 2 in XYZ
23904 tests in 2 items.
23913 passed and 1 failed.
2392***Test Failed*** 1 failures.
2393(1, 4)
2394"""
2395
2396def test2(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002397 >>> warnings.filterwarnings("ignore", "class Tester",
2398 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002399 >>> t = Tester(globs={}, verbose=1)
2400 >>> test = r'''
2401 ... # just an example
2402 ... >>> x = 1 + 2
2403 ... >>> x
2404 ... 3
2405 ... '''
2406 >>> t.runstring(test, "Example")
2407 Running string Example
2408 Trying: x = 1 + 2
2409 Expecting: nothing
2410 ok
2411 Trying: x
2412 Expecting: 3
2413 ok
2414 0 of 2 examples failed in string Example
2415 (0, 2)
2416"""
2417def test3(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002418 >>> warnings.filterwarnings("ignore", "class Tester",
2419 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002420 >>> t = Tester(globs={}, verbose=0)
2421 >>> def _f():
2422 ... '''Trivial docstring example.
2423 ... >>> assert 2 == 2
2424 ... '''
2425 ... return 32
2426 ...
2427 >>> t.rundoc(_f) # expect 0 failures in 1 example
2428 (0, 1)
2429"""
2430def test4(): """
2431 >>> import new
2432 >>> m1 = new.module('_m1')
2433 >>> m2 = new.module('_m2')
2434 >>> test_data = \"""
2435 ... def _f():
2436 ... '''>>> assert 1 == 1
2437 ... '''
2438 ... def g():
2439 ... '''>>> assert 2 != 1
2440 ... '''
2441 ... class H:
2442 ... '''>>> assert 2 > 1
2443 ... '''
2444 ... def bar(self):
2445 ... '''>>> assert 1 < 2
2446 ... '''
2447 ... \"""
2448 >>> exec test_data in m1.__dict__
2449 >>> exec test_data in m2.__dict__
2450 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2451
2452 Tests that objects outside m1 are excluded:
2453
Tim Peters3ddd60a2004-08-08 02:43:33 +00002454 >>> warnings.filterwarnings("ignore", "class Tester",
2455 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002456 >>> t = Tester(globs={}, verbose=0)
Tim Petersf727c6c2004-08-08 01:48:59 +00002457 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Tim Peters8485b562004-08-04 18:46:34 +00002458 (0, 4)
2459
Tim Petersf727c6c2004-08-08 01:48:59 +00002460 Once more, not excluding stuff outside m1:
Tim Peters8485b562004-08-04 18:46:34 +00002461
2462 >>> t = Tester(globs={}, verbose=0)
2463 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2464 (0, 8)
2465
2466 The exclusion of objects from outside the designated module is
2467 meant to be invoked automagically by testmod.
2468
Tim Petersf727c6c2004-08-08 01:48:59 +00002469 >>> testmod(m1, verbose=False)
2470 (0, 4)
Tim Peters8485b562004-08-04 18:46:34 +00002471"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002472
2473def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002474 #import doctest
2475 #doctest.testmod(doctest, verbose=False,
2476 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2477 # UNIFIED_DIFF)
2478 #print '~'*70
2479 r = unittest.TextTestRunner()
2480 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002481
2482if __name__ == "__main__":
2483 _test()