blob: 31c0af8d6e00bd65ad7c3e2197bb0acd73a4a8b6 [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
Tim Petersbb431472004-08-09 03:51:46 +0000370 - source: A single Python statement, always ending with a newline.
371 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000372
Tim Petersbb431472004-08-09 03:51:46 +0000373 - want: The expected output from running the source code (either
374 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
Tim Petersbb431472004-08-09 03:51:46 +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.
381 """
382 def __init__(self, source, want, lineno):
Tim Petersbb431472004-08-09 03:51:46 +0000383 # Normalize inputs.
384 if not source.endswith('\n'):
385 source += '\n'
386 if want and not want.endswith('\n'):
387 want += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000388 # Store properties.
389 self.source = source
390 self.want = want
391 self.lineno = lineno
Tim Peters8a7d2d52001-01-16 07:10:57 +0000392
Tim Peters8485b562004-08-04 18:46:34 +0000393class DocTest:
394 """
395 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000396 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000397
Tim Peters8485b562004-08-04 18:46:34 +0000398 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000399
Tim Peters8485b562004-08-04 18:46:34 +0000400 - globs: The namespace (aka globals) that the examples should
401 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000402
Tim Peters8485b562004-08-04 18:46:34 +0000403 - name: A name identifying the DocTest (typically, the name of
404 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000405
Tim Peters8485b562004-08-04 18:46:34 +0000406 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000407 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000408
Tim Peters8485b562004-08-04 18:46:34 +0000409 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000410 begins, or `None` if the line number is unavailable. This
411 line number is zero-based, with respect to the beginning of
412 the file.
413
414 - docstring: The string that the examples were extracted from,
415 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000416 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000417 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000418 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000419 Create a new DocTest containing the given examples. The
420 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000421 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000422 assert not isinstance(examples, basestring), \
423 "DocTest no longer accepts str; use DocTestParser instead"
424 self.examples = examples
425 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000426 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000427 self.name = name
428 self.filename = filename
429 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000430
431 def __repr__(self):
432 if len(self.examples) == 0:
433 examples = 'no examples'
434 elif len(self.examples) == 1:
435 examples = '1 example'
436 else:
437 examples = '%d examples' % len(self.examples)
438 return ('<DocTest %s from %s:%s (%s)>' %
439 (self.name, self.filename, self.lineno, examples))
440
441
442 # This lets us sort tests by name:
443 def __cmp__(self, other):
444 if not isinstance(other, DocTest):
445 return -1
446 return cmp((self.name, self.filename, self.lineno, id(self)),
447 (other.name, other.filename, other.lineno, id(other)))
448
449######################################################################
Edward Lopera1ef6112004-08-09 16:14:41 +0000450## 2. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000451######################################################################
452
Edward Lopera1ef6112004-08-09 16:14:41 +0000453class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000454 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000455 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000456 """
Edward Loper7c748462004-08-09 02:06:06 +0000457 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000458 # Source consists of a PS1 line followed by zero or more PS2 lines.
459 (?P<source>
460 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
461 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
462 \n?
463 # Want consists of any non-blank lines that do not start with PS1.
464 (?P<want> (?:(?![ ]*$) # Not a blank line
465 (?![ ]*>>>) # Not a line starting with PS1
466 .*$\n? # But any other line
467 )*)
468 ''', re.MULTILINE | re.VERBOSE)
469 _IS_BLANK_OR_COMMENT = re.compile('^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000470
Edward Lopera1ef6112004-08-09 16:14:41 +0000471 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000472 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000473 Extract all doctest examples from the given string, and
474 collect them into a `DocTest` object.
475
476 `globs`, `name`, `filename`, and `lineno` are attributes for
477 the new `DocTest` object. See the documentation for `DocTest`
478 for more information.
479 """
480 return DocTest(self.get_examples(string, name), globs,
481 name, filename, lineno, string)
482
483 def get_examples(self, string, name='<string>'):
484 """
485 Extract all doctest examples from the given string, and return
486 them as a list of `Example` objects. Line numbers are
487 0-based, because it's most common in doctests that nothing
488 interesting appears on the same line as opening triple-quote,
489 and so the first interesting line is called \"line 1\" then.
490
491 The optional argument `name` is a name identifying this
492 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000493
494 >>> text = '''
495 ... >>> x, y = 2, 3 # no output expected
496 ... >>> if 1:
497 ... ... print x
498 ... ... print y
499 ... 2
500 ... 3
501 ...
502 ... Some text.
503 ... >>> x+y
504 ... 5
505 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000506 >>> for x in DocTestParser().get_examples(text):
Edward Loper78b58f32004-08-09 02:56:02 +0000507 ... print (x.source, x.want, x.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000508 ('x, y = 2, 3 # no output expected\\n', '', 1)
Edward Loper7c748462004-08-09 02:06:06 +0000509 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
Tim Petersbb431472004-08-09 03:51:46 +0000510 ('x+y\\n', '5\\n', 9)
Edward Loper7c748462004-08-09 02:06:06 +0000511 """
512 examples = []
513 charno, lineno = 0, 0
514 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000515 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000516 # Update lineno (lines before this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000517 lineno += string.count('\n', charno, m.start())
Edward Loper7c748462004-08-09 02:06:06 +0000518
519 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000520 (source, want) = self._parse_example(m, name, lineno)
Tim Petersd40a92b2004-08-09 03:28:45 +0000521 if self._IS_BLANK_OR_COMMENT(source):
Edward Loper7c748462004-08-09 02:06:06 +0000522 continue
Edward Loper78b58f32004-08-09 02:56:02 +0000523 examples.append( Example(source, want, lineno) )
Edward Loper7c748462004-08-09 02:06:06 +0000524
525 # Update lineno (lines inside this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000526 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000527 # Update charno.
528 charno = m.end()
529 return examples
530
Edward Lopera1ef6112004-08-09 16:14:41 +0000531 def get_program(self, string, name="<string>"):
Edward Loper7c748462004-08-09 02:06:06 +0000532 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000533 Return an executable program from the given string, as a string.
Edward Loper7c748462004-08-09 02:06:06 +0000534
535 The format of this isn't rigidly defined. In general, doctest
536 examples become the executable statements in the result, and
537 their expected outputs become comments, preceded by an \"#Expected:\"
538 comment. Everything else (text, comments, everything not part of
539 a doctest test) is also placed in comments.
540
Edward Lopera1ef6112004-08-09 16:14:41 +0000541 The optional argument `name` is a name identifying this
542 string, and is only used for error messages.
543
Edward Loper7c748462004-08-09 02:06:06 +0000544 >>> text = '''
545 ... >>> x, y = 2, 3 # no output expected
546 ... >>> if 1:
547 ... ... print x
548 ... ... print y
549 ... 2
550 ... 3
551 ...
552 ... Some text.
553 ... >>> x+y
554 ... 5
555 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000556 >>> print DocTestParser().get_program(text)
Edward Loper7c748462004-08-09 02:06:06 +0000557 x, y = 2, 3 # no output expected
558 if 1:
559 print x
560 print y
561 # Expected:
562 # 2
563 # 3
564 #
565 # Some text.
566 x+y
567 # Expected:
568 # 5
569 """
570 output = []
571 charnum, lineno = 0, 0
572 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000573 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000574 # Add any text before this example, as a comment.
575 if m.start() > charnum:
Edward Lopera1ef6112004-08-09 16:14:41 +0000576 lines = string[charnum:m.start()-1].split('\n')
Edward Loper7c748462004-08-09 02:06:06 +0000577 output.extend([self._comment_line(l) for l in lines])
578 lineno += len(lines)
579
580 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000581 (source, want) = self._parse_example(m, name, lineno, False)
Edward Loper7c748462004-08-09 02:06:06 +0000582 # Display the source
583 output.append(source)
584 # Display the expected output, if any
585 if want:
586 output.append('# Expected:')
587 output.extend(['# '+l for l in want.split('\n')])
588
589 # Update the line number & char number.
Edward Lopera1ef6112004-08-09 16:14:41 +0000590 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000591 charnum = m.end()
592 # Add any remaining text, as comments.
593 output.extend([self._comment_line(l)
Edward Lopera1ef6112004-08-09 16:14:41 +0000594 for l in string[charnum:].split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000595 # Trim junk on both ends.
596 while output and output[-1] == '#':
597 output.pop()
598 while output and output[0] == '#':
599 output.pop(0)
600 # Combine the output, and return it.
601 return '\n'.join(output)
602
Edward Lopera1ef6112004-08-09 16:14:41 +0000603 def _parse_example(self, m, name, lineno, add_newlines=True):
Edward Loper7c748462004-08-09 02:06:06 +0000604 # Get the example's indentation level.
605 indent = len(m.group('indent'))
606
607 # Divide source into lines; check that they're properly
608 # indented; and then strip their indentation & prompts.
609 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000610 self._check_prompt_blank(source_lines, indent, name, lineno)
611 self._check_prefix(source_lines[1:], ' '*indent+'.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000612 source = '\n'.join([sl[indent+4:] for sl in source_lines])
613 if len(source_lines) > 1 and add_newlines:
614 source += '\n'
615
616 # Divide want into lines; check that it's properly
617 # indented; and then strip the indentation.
618 want_lines = m.group('want').rstrip().split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000619 self._check_prefix(want_lines, ' '*indent, name,
Edward Loper7c748462004-08-09 02:06:06 +0000620 lineno+len(source_lines))
621 want = '\n'.join([wl[indent:] for wl in want_lines])
622 if len(want) > 0 and add_newlines:
623 want += '\n'
624
625 return source, want
626
627 def _comment_line(self, line):
628 line = line.rstrip()
Tim Petersdd0e4752004-08-09 03:31:56 +0000629 if line:
630 return '# '+line
631 else:
632 return '#'
Edward Loper7c748462004-08-09 02:06:06 +0000633
Edward Lopera1ef6112004-08-09 16:14:41 +0000634 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000635 for i, line in enumerate(lines):
636 if len(line) >= indent+4 and line[indent+3] != ' ':
637 raise ValueError('line %r of the docstring for %s '
638 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000639 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000640 line[indent:indent+3], line))
641
Edward Lopera1ef6112004-08-09 16:14:41 +0000642 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000643 for i, line in enumerate(lines):
644 if line and not line.startswith(prefix):
645 raise ValueError('line %r of the docstring for %s has '
646 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000647 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000648
649
650######################################################################
651## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000652######################################################################
653
654class DocTestFinder:
655 """
656 A class used to extract the DocTests that are relevant to a given
657 object, from its docstring and the docstrings of its contained
658 objects. Doctests can currently be extracted from the following
659 object types: modules, functions, classes, methods, staticmethods,
660 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000661 """
662
Edward Lopera1ef6112004-08-09 16:14:41 +0000663 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000664 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000665 """
666 Create a new doctest finder.
667
Edward Lopera1ef6112004-08-09 16:14:41 +0000668 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000669 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000670 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000671 signature for this factory function should match the signature
672 of the DocTest constructor.
673
Tim Peters8485b562004-08-04 18:46:34 +0000674 If the optional argument `recurse` is false, then `find` will
675 only examine the given object, and not any contained objects.
676 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000677 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000678 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000679 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000680 # _namefilter is undocumented, and exists only for temporary backward-
681 # compatibility support of testmod's deprecated isprivate mess.
682 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000683
684 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000685 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000686 """
687 Return a list of the DocTests that are defined by the given
688 object's docstring, or by any of its contained objects'
689 docstrings.
690
691 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000692 the given object. If the module is not specified or is None, then
693 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000694 correct module. The object's module is used:
695
696 - As a default namespace, if `globs` is not specified.
697 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000698 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000699 - To find the name of the file containing the object.
700 - To help find the line number of the object within its
701 file.
702
Tim Petersf3f57472004-08-08 06:11:48 +0000703 Contained objects whose module does not match `module` are ignored.
704
705 If `module` is False, no attempt to find the module will be made.
706 This is obscure, of use mostly in tests: if `module` is False, or
707 is None but cannot be found automatically, then all objects are
708 considered to belong to the (non-existent) module, so all contained
709 objects will (recursively) be searched for doctests.
710
Tim Peters8485b562004-08-04 18:46:34 +0000711 The globals for each DocTest is formed by combining `globs`
712 and `extraglobs` (bindings in `extraglobs` override bindings
713 in `globs`). A new copy of the globals dictionary is created
714 for each DocTest. If `globs` is not specified, then it
715 defaults to the module's `__dict__`, if specified, or {}
716 otherwise. If `extraglobs` is not specified, then it defaults
717 to {}.
718
Tim Peters8485b562004-08-04 18:46:34 +0000719 """
720 # If name was not specified, then extract it from the object.
721 if name is None:
722 name = getattr(obj, '__name__', None)
723 if name is None:
724 raise ValueError("DocTestFinder.find: name must be given "
725 "when obj.__name__ doesn't exist: %r" %
726 (type(obj),))
727
728 # Find the module that contains the given object (if obj is
729 # a module, then module=obj.). Note: this may fail, in which
730 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000731 if module is False:
732 module = None
733 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000734 module = inspect.getmodule(obj)
735
736 # Read the module's source code. This is used by
737 # DocTestFinder._find_lineno to find the line number for a
738 # given object's docstring.
739 try:
740 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
741 source_lines = linecache.getlines(file)
742 if not source_lines:
743 source_lines = None
744 except TypeError:
745 source_lines = None
746
747 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000748 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000749 if module is None:
750 globs = {}
751 else:
752 globs = module.__dict__.copy()
753 else:
754 globs = globs.copy()
755 if extraglobs is not None:
756 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000757
Tim Peters8485b562004-08-04 18:46:34 +0000758 # Recursively expore `obj`, extracting DocTests.
759 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000760 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000761 return tests
762
763 def _filter(self, obj, prefix, base):
764 """
765 Return true if the given object should not be examined.
766 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000767 return (self._namefilter is not None and
768 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000769
770 def _from_module(self, module, object):
771 """
772 Return true if the given object is defined in the given
773 module.
774 """
775 if module is None:
776 return True
777 elif inspect.isfunction(object):
778 return module.__dict__ is object.func_globals
779 elif inspect.isclass(object):
780 return module.__name__ == object.__module__
781 elif inspect.getmodule(object) is not None:
782 return module is inspect.getmodule(object)
783 elif hasattr(object, '__module__'):
784 return module.__name__ == object.__module__
785 elif isinstance(object, property):
786 return True # [XX] no way not be sure.
787 else:
788 raise ValueError("object must be a class or function")
789
Tim Petersf3f57472004-08-08 06:11:48 +0000790 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000791 """
792 Find tests for the given object and any contained objects, and
793 add them to `tests`.
794 """
795 if self._verbose:
796 print 'Finding tests in %s' % name
797
798 # If we've already processed this object, then ignore it.
799 if id(obj) in seen:
800 return
801 seen[id(obj)] = 1
802
803 # Find a test for this object, and add it to the list of tests.
804 test = self._get_test(obj, name, module, globs, source_lines)
805 if test is not None:
806 tests.append(test)
807
808 # Look for tests in a module's contained objects.
809 if inspect.ismodule(obj) and self._recurse:
810 for valname, val in obj.__dict__.items():
811 # Check if this contained object should be ignored.
812 if self._filter(val, name, valname):
813 continue
814 valname = '%s.%s' % (name, valname)
815 # Recurse to functions & classes.
816 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000817 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000818 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000819 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000820
821 # Look for tests in a module's __test__ dictionary.
822 if inspect.ismodule(obj) and self._recurse:
823 for valname, val in getattr(obj, '__test__', {}).items():
824 if not isinstance(valname, basestring):
825 raise ValueError("DocTestFinder.find: __test__ keys "
826 "must be strings: %r" %
827 (type(valname),))
828 if not (inspect.isfunction(val) or inspect.isclass(val) or
829 inspect.ismethod(val) or inspect.ismodule(val) or
830 isinstance(val, basestring)):
831 raise ValueError("DocTestFinder.find: __test__ values "
832 "must be strings, functions, methods, "
833 "classes, or modules: %r" %
834 (type(val),))
835 valname = '%s.%s' % (name, valname)
836 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000837 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000838
839 # Look for tests in a class's contained objects.
840 if inspect.isclass(obj) and self._recurse:
841 for valname, val in obj.__dict__.items():
842 # Check if this contained object should be ignored.
843 if self._filter(val, name, valname):
844 continue
845 # Special handling for staticmethod/classmethod.
846 if isinstance(val, staticmethod):
847 val = getattr(obj, valname)
848 if isinstance(val, classmethod):
849 val = getattr(obj, valname).im_func
850
851 # Recurse to methods, properties, and nested classes.
852 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +0000853 isinstance(val, property)) and
854 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000855 valname = '%s.%s' % (name, valname)
856 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000857 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000858
859 def _get_test(self, obj, name, module, globs, source_lines):
860 """
861 Return a DocTest for the given object, if it defines a docstring;
862 otherwise, return None.
863 """
864 # Extract the object's docstring. If it doesn't have one,
865 # then return None (no test for this object).
866 if isinstance(obj, basestring):
867 docstring = obj
868 else:
869 try:
870 if obj.__doc__ is None:
871 return None
872 docstring = str(obj.__doc__)
873 except (TypeError, AttributeError):
874 return None
875
876 # Don't bother if the docstring is empty.
877 if not docstring:
878 return None
879
880 # Find the docstring's location in the file.
881 lineno = self._find_lineno(obj, source_lines)
882
883 # Return a DocTest for this object.
884 if module is None:
885 filename = None
886 else:
887 filename = getattr(module, '__file__', module.__name__)
Edward Lopera1ef6112004-08-09 16:14:41 +0000888 return self._parser.get_doctest(docstring, globs, name,
889 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +0000890
891 def _find_lineno(self, obj, source_lines):
892 """
893 Return a line number of the given object's docstring. Note:
894 this method assumes that the object has a docstring.
895 """
896 lineno = None
897
898 # Find the line number for modules.
899 if inspect.ismodule(obj):
900 lineno = 0
901
902 # Find the line number for classes.
903 # Note: this could be fooled if a class is defined multiple
904 # times in a single file.
905 if inspect.isclass(obj):
906 if source_lines is None:
907 return None
908 pat = re.compile(r'^\s*class\s*%s\b' %
909 getattr(obj, '__name__', '-'))
910 for i, line in enumerate(source_lines):
911 if pat.match(line):
912 lineno = i
913 break
914
915 # Find the line number for functions & methods.
916 if inspect.ismethod(obj): obj = obj.im_func
917 if inspect.isfunction(obj): obj = obj.func_code
918 if inspect.istraceback(obj): obj = obj.tb_frame
919 if inspect.isframe(obj): obj = obj.f_code
920 if inspect.iscode(obj):
921 lineno = getattr(obj, 'co_firstlineno', None)-1
922
923 # Find the line number where the docstring starts. Assume
924 # that it's the first line that begins with a quote mark.
925 # Note: this could be fooled by a multiline function
926 # signature, where a continuation line begins with a quote
927 # mark.
928 if lineno is not None:
929 if source_lines is None:
930 return lineno+1
931 pat = re.compile('(^|.*:)\s*\w*("|\')')
932 for lineno in range(lineno, len(source_lines)):
933 if pat.match(source_lines[lineno]):
934 return lineno
935
936 # We couldn't find the line number.
937 return None
938
939######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000940## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +0000941######################################################################
942
Tim Peters8485b562004-08-04 18:46:34 +0000943class DocTestRunner:
944 """
945 A class used to run DocTest test cases, and accumulate statistics.
946 The `run` method is used to process a single DocTest case. It
947 returns a tuple `(f, t)`, where `t` is the number of test cases
948 tried, and `f` is the number of test cases that failed.
949
950 >>> tests = DocTestFinder().find(_TestClass)
951 >>> runner = DocTestRunner(verbose=False)
952 >>> for test in tests:
953 ... print runner.run(test)
954 (0, 2)
955 (0, 1)
956 (0, 2)
957 (0, 2)
958
959 The `summarize` method prints a summary of all the test cases that
960 have been run by the runner, and returns an aggregated `(f, t)`
961 tuple:
962
963 >>> runner.summarize(verbose=1)
964 4 items passed all tests:
965 2 tests in _TestClass
966 2 tests in _TestClass.__init__
967 2 tests in _TestClass.get
968 1 tests in _TestClass.square
969 7 tests in 4 items.
970 7 passed and 0 failed.
971 Test passed.
972 (0, 7)
973
974 The aggregated number of tried examples and failed examples is
975 also available via the `tries` and `failures` attributes:
976
977 >>> runner.tries
978 7
979 >>> runner.failures
980 0
981
982 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +0000983 by an `OutputChecker`. This comparison may be customized with a
984 number of option flags; see the documentation for `testmod` for
985 more information. If the option flags are insufficient, then the
986 comparison may also be customized by passing a subclass of
987 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +0000988
989 The test runner's display output can be controlled in two ways.
990 First, an output function (`out) can be passed to
991 `TestRunner.run`; this function will be called with strings that
992 should be displayed. It defaults to `sys.stdout.write`. If
993 capturing the output is not sufficient, then the display output
994 can be also customized by subclassing DocTestRunner, and
995 overriding the methods `report_start`, `report_success`,
996 `report_unexpected_exception`, and `report_failure`.
997 """
998 # This divider string is used to separate failure messages, and to
999 # separate sections of the summary.
1000 DIVIDER = "*" * 70
1001
Edward Loper34fcb142004-08-09 02:45:41 +00001002 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001003 """
1004 Create a new test runner.
1005
Edward Loper34fcb142004-08-09 02:45:41 +00001006 Optional keyword arg `checker` is the `OutputChecker` that
1007 should be used to compare the expected outputs and actual
1008 outputs of doctest examples.
1009
Tim Peters8485b562004-08-04 18:46:34 +00001010 Optional keyword arg 'verbose' prints lots of stuff if true,
1011 only failures if false; by default, it's true iff '-v' is in
1012 sys.argv.
1013
1014 Optional argument `optionflags` can be used to control how the
1015 test runner compares expected output to actual output, and how
1016 it displays failures. See the documentation for `testmod` for
1017 more information.
1018 """
Edward Loper34fcb142004-08-09 02:45:41 +00001019 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001020 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001021 verbose = '-v' in sys.argv
1022 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001023 self.optionflags = optionflags
1024
Tim Peters8485b562004-08-04 18:46:34 +00001025 # Keep track of the examples we've run.
1026 self.tries = 0
1027 self.failures = 0
1028 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001029
Tim Peters8485b562004-08-04 18:46:34 +00001030 # Create a fake output target for capturing doctest output.
1031 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001032
Tim Peters8485b562004-08-04 18:46:34 +00001033 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001034 # Reporting methods
1035 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001036
Tim Peters8485b562004-08-04 18:46:34 +00001037 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001038 """
Tim Peters8485b562004-08-04 18:46:34 +00001039 Report that the test runner is about to process the given
1040 example. (Only displays a message if verbose=True)
1041 """
1042 if self._verbose:
1043 out(_tag_msg("Trying", example.source) +
1044 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001045
Tim Peters8485b562004-08-04 18:46:34 +00001046 def report_success(self, out, test, example, got):
1047 """
1048 Report that the given example ran successfully. (Only
1049 displays a message if verbose=True)
1050 """
1051 if self._verbose:
1052 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001053
Tim Peters8485b562004-08-04 18:46:34 +00001054 def report_failure(self, out, test, example, got):
1055 """
1056 Report that the given example failed.
1057 """
1058 # Print an error message.
1059 out(self.__failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001060 self._checker.output_difference(example.want, got,
1061 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001062
Tim Peters8485b562004-08-04 18:46:34 +00001063 def report_unexpected_exception(self, out, test, example, exc_info):
1064 """
1065 Report that the given example raised an unexpected exception.
1066 """
1067 # Get a traceback message.
1068 excout = StringIO()
1069 exc_type, exc_val, exc_tb = exc_info
1070 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
1071 exception_tb = excout.getvalue()
1072 # Print an error message.
1073 out(self.__failure_header(test, example) +
1074 _tag_msg("Exception raised", exception_tb))
Tim Peters7402f792001-10-02 03:53:41 +00001075
Tim Peters8485b562004-08-04 18:46:34 +00001076 def __failure_header(self, test, example):
1077 s = (self.DIVIDER + "\n" +
1078 _tag_msg("Failure in example", example.source))
1079 if test.filename is None:
1080 # [XX] I'm not putting +1 here, to give the same output
1081 # as the old version. But I think it *should* go here.
1082 return s + ("from line #%s of %s\n" %
1083 (example.lineno, test.name))
1084 elif test.lineno is None:
1085 return s + ("from line #%s of %s in %s\n" %
1086 (example.lineno+1, test.name, test.filename))
1087 else:
1088 lineno = test.lineno+example.lineno+1
1089 return s + ("from line #%s of %s (%s)\n" %
1090 (lineno, test.filename, test.name))
Tim Peters7402f792001-10-02 03:53:41 +00001091
Tim Peters8485b562004-08-04 18:46:34 +00001092 #/////////////////////////////////////////////////////////////////
1093 # DocTest Running
1094 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001095
Tim Peters8485b562004-08-04 18:46:34 +00001096 # A regular expression for handling `want` strings that contain
1097 # expected exceptions. It divides `want` into two pieces: the
1098 # pre-exception output (`out`) and the exception message (`exc`),
1099 # as generated by traceback.format_exception_only(). (I assume
1100 # that the exception_only message is the first non-indented line
1101 # starting with word characters after the "Traceback ...".)
1102 _EXCEPTION_RE = re.compile(('^(?P<out>.*)'
1103 '^(?P<hdr>Traceback \((?:%s|%s)\):)\s*$.*?'
1104 '^(?P<exc>\w+.*)') %
1105 ('most recent call last', 'innermost last'),
1106 re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001107
Tim Peters8485b562004-08-04 18:46:34 +00001108 _OPTION_DIRECTIVE_RE = re.compile('\s*doctest:\s*(?P<flags>[^#\n]*)')
Tim Peters7402f792001-10-02 03:53:41 +00001109
Tim Peters8485b562004-08-04 18:46:34 +00001110 def __handle_directive(self, example):
1111 """
1112 Check if the given example is actually a directive to doctest
1113 (to turn an optionflag on or off); and if it is, then handle
1114 the directive.
Tim Peters7402f792001-10-02 03:53:41 +00001115
Tim Peters8485b562004-08-04 18:46:34 +00001116 Return true iff the example is actually a directive (and so
1117 should not be executed).
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001118
Tim Peters8a7d2d52001-01-16 07:10:57 +00001119 """
Tim Peters8485b562004-08-04 18:46:34 +00001120 m = self._OPTION_DIRECTIVE_RE.match(example.source)
1121 if m is None:
1122 return False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001123
Tim Peters8485b562004-08-04 18:46:34 +00001124 for flag in m.group('flags').upper().split():
1125 if (flag[:1] not in '+-' or
1126 flag[1:] not in OPTIONFLAGS_BY_NAME):
1127 raise ValueError('Bad doctest option directive: '+flag)
1128 if flag[0] == '+':
1129 self.optionflags |= OPTIONFLAGS_BY_NAME[flag[1:]]
1130 else:
1131 self.optionflags &= ~OPTIONFLAGS_BY_NAME[flag[1:]]
1132 return True
Tim Peters8a7d2d52001-01-16 07:10:57 +00001133
Tim Peters8485b562004-08-04 18:46:34 +00001134 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001135 """
Tim Peters8485b562004-08-04 18:46:34 +00001136 Run the examples in `test`. Write the outcome of each example
1137 with one of the `DocTestRunner.report_*` methods, using the
1138 writer function `out`. `compileflags` is the set of compiler
1139 flags that should be used to execute examples. Return a tuple
1140 `(f, t)`, where `t` is the number of examples tried, and `f`
1141 is the number of examples that failed. The examples are run
1142 in the namespace `test.globs`.
1143 """
1144 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001145 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001146
1147 # Save the option flags (since option directives can be used
1148 # to modify them).
1149 original_optionflags = self.optionflags
1150
1151 # Process each example.
1152 for example in test.examples:
1153 # Check if it's an option directive. If it is, then handle
1154 # it, and go on to the next example.
1155 if self.__handle_directive(example):
1156 continue
1157
1158 # Record that we started this example.
1159 tries += 1
1160 self.report_start(out, test, example)
1161
1162 # Run the example in the given context (globs), and record
1163 # any exception that gets raised. (But don't intercept
1164 # keyboard interrupts.)
1165 try:
Tim Peters208ca702004-08-09 04:12:36 +00001166 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001167 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001168 compileflags, 1) in test.globs
1169 exception = None
1170 except KeyboardInterrupt:
1171 raise
1172 except:
1173 exception = sys.exc_info()
1174
Tim Peters208ca702004-08-09 04:12:36 +00001175 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001176 self._fakeout.truncate(0)
1177
1178 # If the example executed without raising any exceptions,
1179 # then verify its output and report its outcome.
1180 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001181 if self._checker.check_output(example.want, got,
1182 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001183 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001184 else:
Tim Peters8485b562004-08-04 18:46:34 +00001185 self.report_failure(out, test, example, got)
1186 failures += 1
1187
1188 # If the example raised an exception, then check if it was
1189 # expected.
1190 else:
1191 exc_info = sys.exc_info()
1192 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1193
1194 # Search the `want` string for an exception. If we don't
1195 # find one, then report an unexpected exception.
1196 m = self._EXCEPTION_RE.match(example.want)
1197 if m is None:
1198 self.report_unexpected_exception(out, test, example,
1199 exc_info)
1200 failures += 1
1201 else:
1202 exc_hdr = m.group('hdr')+'\n' # Exception header
1203 # The test passes iff the pre-exception output and
1204 # the exception description match the values given
1205 # in `want`.
Edward Loper34fcb142004-08-09 02:45:41 +00001206 if (self._checker.check_output(m.group('out'), got,
1207 self.optionflags) and
1208 self._checker.check_output(m.group('exc'), exc_msg,
1209 self.optionflags)):
Tim Peters8485b562004-08-04 18:46:34 +00001210 # Is +exc_msg the right thing here??
1211 self.report_success(out, test, example,
1212 got+exc_hdr+exc_msg)
1213 else:
1214 self.report_failure(out, test, example,
1215 got+exc_hdr+exc_msg)
1216 failures += 1
1217
1218 # Restore the option flags (in case they were modified)
1219 self.optionflags = original_optionflags
1220
1221 # Record and return the number of failures and tries.
1222 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001223 return failures, tries
1224
Tim Peters8485b562004-08-04 18:46:34 +00001225 def __record_outcome(self, test, f, t):
1226 """
1227 Record the fact that the given DocTest (`test`) generated `f`
1228 failures out of `t` tried examples.
1229 """
1230 f2, t2 = self._name2ft.get(test.name, (0,0))
1231 self._name2ft[test.name] = (f+f2, t+t2)
1232 self.failures += f
1233 self.tries += t
1234
1235 def run(self, test, compileflags=None, out=None, clear_globs=True):
1236 """
1237 Run the examples in `test`, and display the results using the
1238 writer function `out`.
1239
1240 The examples are run in the namespace `test.globs`. If
1241 `clear_globs` is true (the default), then this namespace will
1242 be cleared after the test runs, to help with garbage
1243 collection. If you would like to examine the namespace after
1244 the test completes, then use `clear_globs=False`.
1245
1246 `compileflags` gives the set of flags that should be used by
1247 the Python compiler when running the examples. If not
1248 specified, then it will default to the set of future-import
1249 flags that apply to `globs`.
1250
1251 The output of each example is checked using
1252 `DocTestRunner.check_output`, and the results are formatted by
1253 the `DocTestRunner.report_*` methods.
1254 """
1255 if compileflags is None:
1256 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001257
Tim Peters6c542b72004-08-09 16:43:36 +00001258 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001259 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001260 out = save_stdout.write
1261 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001262
Tim Peters6c542b72004-08-09 16:43:36 +00001263 # Patch pdb.set_trace to restore sys.stdout, so that interactive
1264 # debugging output is visible (not still redirected to self._fakeout).
1265 # Note that we run "the real" pdb.set_trace (captured at doctest
1266 # import time) in our replacement. Because the current run() may
1267 # run another doctest (and so on), the current pdb.set_trace may be
1268 # our set_trace function, which changes sys.stdout. If we called
1269 # a chain of those, we wouldn't be left with the save_stdout
1270 # *this* run() invocation wants.
Jim Fulton356fd192004-08-09 11:34:47 +00001271 def set_trace():
Tim Peters6c542b72004-08-09 16:43:36 +00001272 sys.stdout = save_stdout
Jim Fulton356fd192004-08-09 11:34:47 +00001273 real_pdb_set_trace()
1274
Tim Peters6c542b72004-08-09 16:43:36 +00001275 save_set_trace = pdb.set_trace
1276 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001277 try:
Tim Peters8485b562004-08-04 18:46:34 +00001278 return self.__run(test, compileflags, out)
1279 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001280 sys.stdout = save_stdout
1281 pdb.set_trace = save_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001282 if clear_globs:
1283 test.globs.clear()
1284
1285 #/////////////////////////////////////////////////////////////////
1286 # Summarization
1287 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001288 def summarize(self, verbose=None):
1289 """
Tim Peters8485b562004-08-04 18:46:34 +00001290 Print a summary of all the test cases that have been run by
1291 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1292 the total number of failed examples, and `t` is the total
1293 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001294
Tim Peters8485b562004-08-04 18:46:34 +00001295 The optional `verbose` argument controls how detailed the
1296 summary is. If the verbosity is not specified, then the
1297 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001298 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001299 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001300 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001301 notests = []
1302 passed = []
1303 failed = []
1304 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001305 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001306 name, (f, t) = x
1307 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001308 totalt += t
1309 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001310 if t == 0:
1311 notests.append(name)
1312 elif f == 0:
1313 passed.append( (name, t) )
1314 else:
1315 failed.append(x)
1316 if verbose:
1317 if notests:
1318 print len(notests), "items had no tests:"
1319 notests.sort()
1320 for thing in notests:
1321 print " ", thing
1322 if passed:
1323 print len(passed), "items passed all tests:"
1324 passed.sort()
1325 for thing, count in passed:
1326 print " %3d tests in %s" % (count, thing)
1327 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001328 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001329 print len(failed), "items had failures:"
1330 failed.sort()
1331 for thing, (f, t) in failed:
1332 print " %3d of %3d in %s" % (f, t, thing)
1333 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001334 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001335 print totalt - totalf, "passed and", totalf, "failed."
1336 if totalf:
1337 print "***Test Failed***", totalf, "failures."
1338 elif verbose:
1339 print "Test passed."
1340 return totalf, totalt
1341
Edward Loper34fcb142004-08-09 02:45:41 +00001342class OutputChecker:
1343 """
1344 A class used to check the whether the actual output from a doctest
1345 example matches the expected output. `OutputChecker` defines two
1346 methods: `check_output`, which compares a given pair of outputs,
1347 and returns true if they match; and `output_difference`, which
1348 returns a string describing the differences between two outputs.
1349 """
1350 def check_output(self, want, got, optionflags):
1351 """
1352 Return True iff the actual output (`got`) matches the expected
1353 output (`want`). These strings are always considered to match
1354 if they are identical; but depending on what option flags the
1355 test runner is using, several non-exact match types are also
1356 possible. See the documentation for `TestRunner` for more
1357 information about option flags.
1358 """
1359 # Handle the common case first, for efficiency:
1360 # if they're string-identical, always return true.
1361 if got == want:
1362 return True
1363
1364 # The values True and False replaced 1 and 0 as the return
1365 # value for boolean comparisons in Python 2.3.
1366 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1367 if (got,want) == ("True\n", "1\n"):
1368 return True
1369 if (got,want) == ("False\n", "0\n"):
1370 return True
1371
1372 # <BLANKLINE> can be used as a special sequence to signify a
1373 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1374 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1375 # Replace <BLANKLINE> in want with a blank line.
1376 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1377 '', want)
1378 # If a line in got contains only spaces, then remove the
1379 # spaces.
1380 got = re.sub('(?m)^\s*?$', '', got)
1381 if got == want:
1382 return True
1383
1384 # This flag causes doctest to ignore any differences in the
1385 # contents of whitespace strings. Note that this can be used
1386 # in conjunction with the ELLISPIS flag.
1387 if (optionflags & NORMALIZE_WHITESPACE):
1388 got = ' '.join(got.split())
1389 want = ' '.join(want.split())
1390 if got == want:
1391 return True
1392
1393 # The ELLIPSIS flag says to let the sequence "..." in `want`
1394 # match any substring in `got`. We implement this by
1395 # transforming `want` into a regular expression.
1396 if (optionflags & ELLIPSIS):
1397 # Escape any special regexp characters
1398 want_re = re.escape(want)
1399 # Replace ellipsis markers ('...') with .*
1400 want_re = want_re.replace(re.escape(ELLIPSIS_MARKER), '.*')
1401 # Require that it matches the entire string; and set the
1402 # re.DOTALL flag (with '(?s)').
1403 want_re = '(?s)^%s$' % want_re
1404 # Check if the `want_re` regexp matches got.
1405 if re.match(want_re, got):
1406 return True
1407
1408 # We didn't find any match; return false.
1409 return False
1410
1411 def output_difference(self, want, got, optionflags):
1412 """
1413 Return a string describing the differences between the
1414 expected output (`want`) and the actual output (`got`).
1415 """
1416 # If <BLANKLINE>s are being used, then replace <BLANKLINE>
1417 # with blank lines in the expected output string.
1418 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1419 want = re.sub('(?m)^%s$' % re.escape(BLANKLINE_MARKER), '', want)
1420
1421 # Check if we should use diff. Don't use diff if the actual
1422 # or expected outputs are too short, or if the expected output
1423 # contains an ellipsis marker.
1424 if ((optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and
1425 want.count('\n') > 2 and got.count('\n') > 2 and
1426 not (optionflags & ELLIPSIS and '...' in want)):
1427 # Split want & got into lines.
1428 want_lines = [l+'\n' for l in want.split('\n')]
1429 got_lines = [l+'\n' for l in got.split('\n')]
1430 # Use difflib to find their differences.
1431 if optionflags & UNIFIED_DIFF:
1432 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1433 fromfile='Expected', tofile='Got')
1434 kind = 'unified'
1435 elif optionflags & CONTEXT_DIFF:
1436 diff = difflib.context_diff(want_lines, got_lines, n=2,
1437 fromfile='Expected', tofile='Got')
1438 kind = 'context'
1439 else:
1440 assert 0, 'Bad diff option'
1441 # Remove trailing whitespace on diff output.
1442 diff = [line.rstrip() + '\n' for line in diff]
1443 return _tag_msg("Differences (" + kind + " diff)",
1444 ''.join(diff))
1445
1446 # If we're not using diff, then simply list the expected
1447 # output followed by the actual output.
1448 return (_tag_msg("Expected", want or "Nothing") +
1449 _tag_msg("Got", got))
1450
Tim Peters19397e52004-08-06 22:02:59 +00001451class DocTestFailure(Exception):
1452 """A DocTest example has failed in debugging mode.
1453
1454 The exception instance has variables:
1455
1456 - test: the DocTest object being run
1457
1458 - excample: the Example object that failed
1459
1460 - got: the actual output
1461 """
1462 def __init__(self, test, example, got):
1463 self.test = test
1464 self.example = example
1465 self.got = got
1466
1467 def __str__(self):
1468 return str(self.test)
1469
1470class UnexpectedException(Exception):
1471 """A DocTest example has encountered an unexpected exception
1472
1473 The exception instance has variables:
1474
1475 - test: the DocTest object being run
1476
1477 - excample: the Example object that failed
1478
1479 - exc_info: the exception info
1480 """
1481 def __init__(self, test, example, exc_info):
1482 self.test = test
1483 self.example = example
1484 self.exc_info = exc_info
1485
1486 def __str__(self):
1487 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001488
Tim Peters19397e52004-08-06 22:02:59 +00001489class DebugRunner(DocTestRunner):
1490 r"""Run doc tests but raise an exception as soon as there is a failure.
1491
1492 If an unexpected exception occurs, an UnexpectedException is raised.
1493 It contains the test, the example, and the original exception:
1494
1495 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001496 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1497 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001498 >>> try:
1499 ... runner.run(test)
1500 ... except UnexpectedException, failure:
1501 ... pass
1502
1503 >>> failure.test is test
1504 True
1505
1506 >>> failure.example.want
1507 '42\n'
1508
1509 >>> exc_info = failure.exc_info
1510 >>> raise exc_info[0], exc_info[1], exc_info[2]
1511 Traceback (most recent call last):
1512 ...
1513 KeyError
1514
1515 We wrap the original exception to give the calling application
1516 access to the test and example information.
1517
1518 If the output doesn't match, then a DocTestFailure is raised:
1519
Edward Lopera1ef6112004-08-09 16:14:41 +00001520 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001521 ... >>> x = 1
1522 ... >>> x
1523 ... 2
1524 ... ''', {}, 'foo', 'foo.py', 0)
1525
1526 >>> try:
1527 ... runner.run(test)
1528 ... except DocTestFailure, failure:
1529 ... pass
1530
1531 DocTestFailure objects provide access to the test:
1532
1533 >>> failure.test is test
1534 True
1535
1536 As well as to the example:
1537
1538 >>> failure.example.want
1539 '2\n'
1540
1541 and the actual output:
1542
1543 >>> failure.got
1544 '1\n'
1545
1546 If a failure or error occurs, the globals are left intact:
1547
1548 >>> del test.globs['__builtins__']
1549 >>> test.globs
1550 {'x': 1}
1551
Edward Lopera1ef6112004-08-09 16:14:41 +00001552 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001553 ... >>> x = 2
1554 ... >>> raise KeyError
1555 ... ''', {}, 'foo', 'foo.py', 0)
1556
1557 >>> runner.run(test)
1558 Traceback (most recent call last):
1559 ...
1560 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001561
Tim Peters19397e52004-08-06 22:02:59 +00001562 >>> del test.globs['__builtins__']
1563 >>> test.globs
1564 {'x': 2}
1565
1566 But the globals are cleared if there is no error:
1567
Edward Lopera1ef6112004-08-09 16:14:41 +00001568 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001569 ... >>> x = 2
1570 ... ''', {}, 'foo', 'foo.py', 0)
1571
1572 >>> runner.run(test)
1573 (0, 1)
1574
1575 >>> test.globs
1576 {}
1577
1578 """
1579
1580 def run(self, test, compileflags=None, out=None, clear_globs=True):
1581 r = DocTestRunner.run(self, test, compileflags, out, False)
1582 if clear_globs:
1583 test.globs.clear()
1584 return r
1585
1586 def report_unexpected_exception(self, out, test, example, exc_info):
1587 raise UnexpectedException(test, example, exc_info)
1588
1589 def report_failure(self, out, test, example, got):
1590 raise DocTestFailure(test, example, got)
1591
Tim Peters8485b562004-08-04 18:46:34 +00001592######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001593## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001594######################################################################
1595# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001596
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001597def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001598 report=True, optionflags=0, extraglobs=None,
1599 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001600 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001601 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001602
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001603 Test examples in docstrings in functions and classes reachable
1604 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001605 with m.__doc__. Unless isprivate is specified, private names
1606 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001607
1608 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001609 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001610 function and class docstrings are tested even if the name is private;
1611 strings are tested directly, as if they were docstrings.
1612
1613 Return (#failures, #tests).
1614
1615 See doctest.__doc__ for an overview.
1616
1617 Optional keyword arg "name" gives the name of the module; by default
1618 use m.__name__.
1619
1620 Optional keyword arg "globs" gives a dict to be used as the globals
1621 when executing examples; by default, use m.__dict__. A copy of this
1622 dict is actually used for each docstring, so that each docstring's
1623 examples start with a clean slate.
1624
Tim Peters8485b562004-08-04 18:46:34 +00001625 Optional keyword arg "extraglobs" gives a dictionary that should be
1626 merged into the globals that are used to execute examples. By
1627 default, no extra globals are used. This is new in 2.4.
1628
Tim Peters8a7d2d52001-01-16 07:10:57 +00001629 Optional keyword arg "verbose" prints lots of stuff if true, prints
1630 only failures if false; by default, it's true iff "-v" is in sys.argv.
1631
Tim Peters8a7d2d52001-01-16 07:10:57 +00001632 Optional keyword arg "report" prints a summary at the end when true,
1633 else prints nothing at the end. In verbose mode, the summary is
1634 detailed, else very brief (in fact, empty if all tests passed).
1635
Tim Peters6ebe61f2003-06-27 20:48:05 +00001636 Optional keyword arg "optionflags" or's together module constants,
1637 and defaults to 0. This is new in 2.3. Possible values:
1638
1639 DONT_ACCEPT_TRUE_FOR_1
1640 By default, if an expected output block contains just "1",
1641 an actual output block containing just "True" is considered
1642 to be a match, and similarly for "0" versus "False". When
1643 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1644 is allowed.
1645
Tim Peters8485b562004-08-04 18:46:34 +00001646 DONT_ACCEPT_BLANKLINE
1647 By default, if an expected output block contains a line
1648 containing only the string "<BLANKLINE>", then that line
1649 will match a blank line in the actual output. When
1650 DONT_ACCEPT_BLANKLINE is specified, this substitution is
1651 not allowed.
1652
1653 NORMALIZE_WHITESPACE
1654 When NORMALIZE_WHITESPACE is specified, all sequences of
1655 whitespace are treated as equal. I.e., any sequence of
1656 whitespace within the expected output will match any
1657 sequence of whitespace within the actual output.
1658
1659 ELLIPSIS
1660 When ELLIPSIS is specified, then an ellipsis marker
1661 ("...") in the expected output can match any substring in
1662 the actual output.
1663
1664 UNIFIED_DIFF
1665 When UNIFIED_DIFF is specified, failures that involve
1666 multi-line expected and actual outputs will be displayed
1667 using a unified diff.
1668
1669 CONTEXT_DIFF
1670 When CONTEXT_DIFF is specified, failures that involve
1671 multi-line expected and actual outputs will be displayed
1672 using a context diff.
Tim Peters19397e52004-08-06 22:02:59 +00001673
1674 Optional keyword arg "raise_on_error" raises an exception on the
1675 first unexpected exception or failure. This allows failures to be
1676 post-mortem debugged.
1677
Tim Petersf727c6c2004-08-08 01:48:59 +00001678 Deprecated in Python 2.4:
1679 Optional keyword arg "isprivate" specifies a function used to
1680 determine whether a name is private. The default function is
1681 treat all functions as public. Optionally, "isprivate" can be
1682 set to doctest.is_private to skip over functions marked as private
1683 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001684 """
1685
1686 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001687 Advanced tomfoolery: testmod runs methods of a local instance of
1688 class doctest.Tester, then merges the results into (or creates)
1689 global Tester instance doctest.master. Methods of doctest.master
1690 can be called directly too, if you want to do something unusual.
1691 Passing report=0 to testmod is especially useful then, to delay
1692 displaying a summary. Invoke doctest.master.summarize(verbose)
1693 when you're done fiddling.
1694 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001695 if isprivate is not None:
1696 warnings.warn("the isprivate argument is deprecated; "
1697 "examine DocTestFinder.find() lists instead",
1698 DeprecationWarning)
1699
Tim Peters8485b562004-08-04 18:46:34 +00001700 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001701 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001702 # DWA - m will still be None if this wasn't invoked from the command
1703 # line, in which case the following TypeError is about as good an error
1704 # as we should expect
1705 m = sys.modules.get('__main__')
1706
Tim Peters8485b562004-08-04 18:46:34 +00001707 # Check that we were actually given a module.
1708 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001709 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001710
1711 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001712 if name is None:
1713 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001714
1715 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001716 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001717
1718 if raise_on_error:
1719 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1720 else:
1721 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1722
Tim Peters8485b562004-08-04 18:46:34 +00001723 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1724 runner.run(test)
1725
Tim Peters8a7d2d52001-01-16 07:10:57 +00001726 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001727 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001728
Tim Peters8485b562004-08-04 18:46:34 +00001729 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001730
Tim Peters8485b562004-08-04 18:46:34 +00001731def run_docstring_examples(f, globs, verbose=False, name="NoName",
1732 compileflags=None, optionflags=0):
1733 """
1734 Test examples in the given object's docstring (`f`), using `globs`
1735 as globals. Optional argument `name` is used in failure messages.
1736 If the optional argument `verbose` is true, then generate output
1737 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001738
Tim Peters8485b562004-08-04 18:46:34 +00001739 `compileflags` gives the set of flags that should be used by the
1740 Python compiler when running the examples. If not specified, then
1741 it will default to the set of future-import flags that apply to
1742 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001743
Tim Peters8485b562004-08-04 18:46:34 +00001744 Optional keyword arg `optionflags` specifies options for the
1745 testing and output. See the documentation for `testmod` for more
1746 information.
1747 """
1748 # Find, parse, and run all tests in the given module.
1749 finder = DocTestFinder(verbose=verbose, recurse=False)
1750 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1751 for test in finder.find(f, name, globs=globs):
1752 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001753
Tim Peters8485b562004-08-04 18:46:34 +00001754######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001755## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001756######################################################################
1757# This is provided only for backwards compatibility. It's not
1758# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001759
Tim Peters8485b562004-08-04 18:46:34 +00001760class Tester:
1761 def __init__(self, mod=None, globs=None, verbose=None,
1762 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001763
1764 warnings.warn("class Tester is deprecated; "
1765 "use class doctest.DocTestRunner instead",
1766 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001767 if mod is None and globs is None:
1768 raise TypeError("Tester.__init__: must specify mod or globs")
1769 if mod is not None and not _ismodule(mod):
1770 raise TypeError("Tester.__init__: mod must be a module; %r" %
1771 (mod,))
1772 if globs is None:
1773 globs = mod.__dict__
1774 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001775
Tim Peters8485b562004-08-04 18:46:34 +00001776 self.verbose = verbose
1777 self.isprivate = isprivate
1778 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001779 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001780 self.testrunner = DocTestRunner(verbose=verbose,
1781 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001782
Tim Peters8485b562004-08-04 18:46:34 +00001783 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001784 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001785 if self.verbose:
1786 print "Running string", name
1787 (f,t) = self.testrunner.run(test)
1788 if self.verbose:
1789 print f, "of", t, "examples failed in string", name
1790 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001791
Tim Petersf3f57472004-08-08 06:11:48 +00001792 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001793 f = t = 0
1794 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001795 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001796 for test in tests:
1797 (f2, t2) = self.testrunner.run(test)
1798 (f,t) = (f+f2, t+t2)
1799 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001800
Tim Peters8485b562004-08-04 18:46:34 +00001801 def rundict(self, d, name, module=None):
1802 import new
1803 m = new.module(name)
1804 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001805 if module is None:
1806 module = False
1807 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001808
Tim Peters8485b562004-08-04 18:46:34 +00001809 def run__test__(self, d, name):
1810 import new
1811 m = new.module(name)
1812 m.__test__ = d
1813 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001814
Tim Peters8485b562004-08-04 18:46:34 +00001815 def summarize(self, verbose=None):
1816 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001817
Tim Peters8485b562004-08-04 18:46:34 +00001818 def merge(self, other):
1819 d = self.testrunner._name2ft
1820 for name, (f, t) in other.testrunner._name2ft.items():
1821 if name in d:
1822 print "*** Tester.merge: '" + name + "' in both" \
1823 " testers; summing outcomes."
1824 f2, t2 = d[name]
1825 f = f + f2
1826 t = t + t2
1827 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001828
Tim Peters8485b562004-08-04 18:46:34 +00001829######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001830## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001831######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001832
Tim Peters19397e52004-08-06 22:02:59 +00001833class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001834
Edward Loper34fcb142004-08-09 02:45:41 +00001835 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
1836 checker=None):
Jim Fultona643b652004-07-14 19:06:50 +00001837 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00001838 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00001839 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00001840 self._dt_test = test
1841 self._dt_setUp = setUp
1842 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00001843
Jim Fultona643b652004-07-14 19:06:50 +00001844 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00001845 if self._dt_setUp is not None:
1846 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00001847
1848 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00001849 if self._dt_tearDown is not None:
1850 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00001851
1852 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00001853 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00001854 old = sys.stdout
1855 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00001856 runner = DocTestRunner(optionflags=self._dt_optionflags,
1857 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001858
Jim Fultona643b652004-07-14 19:06:50 +00001859 try:
Tim Peters19397e52004-08-06 22:02:59 +00001860 runner.DIVIDER = "-"*70
1861 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00001862 finally:
1863 sys.stdout = old
1864
1865 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00001866 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00001867
Tim Peters19397e52004-08-06 22:02:59 +00001868 def format_failure(self, err):
1869 test = self._dt_test
1870 if test.lineno is None:
1871 lineno = 'unknown line number'
1872 else:
1873 lineno = 'line %s' % test.lineno
1874 lname = '.'.join(test.name.split('.')[-1:])
1875 return ('Failed doctest test for %s\n'
1876 ' File "%s", line %s, in %s\n\n%s'
1877 % (test.name, test.filename, lineno, lname, err)
1878 )
1879
1880 def debug(self):
1881 r"""Run the test case without results and without catching exceptions
1882
1883 The unit test framework includes a debug method on test cases
1884 and test suites to support post-mortem debugging. The test code
1885 is run in such a way that errors are not caught. This way a
1886 caller can catch the errors and initiate post-mortem debugging.
1887
1888 The DocTestCase provides a debug method that raises
1889 UnexpectedException errors if there is an unexepcted
1890 exception:
1891
Edward Lopera1ef6112004-08-09 16:14:41 +00001892 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00001893 ... {}, 'foo', 'foo.py', 0)
1894 >>> case = DocTestCase(test)
1895 >>> try:
1896 ... case.debug()
1897 ... except UnexpectedException, failure:
1898 ... pass
1899
1900 The UnexpectedException contains the test, the example, and
1901 the original exception:
1902
1903 >>> failure.test is test
1904 True
1905
1906 >>> failure.example.want
1907 '42\n'
1908
1909 >>> exc_info = failure.exc_info
1910 >>> raise exc_info[0], exc_info[1], exc_info[2]
1911 Traceback (most recent call last):
1912 ...
1913 KeyError
1914
1915 If the output doesn't match, then a DocTestFailure is raised:
1916
Edward Lopera1ef6112004-08-09 16:14:41 +00001917 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001918 ... >>> x = 1
1919 ... >>> x
1920 ... 2
1921 ... ''', {}, 'foo', 'foo.py', 0)
1922 >>> case = DocTestCase(test)
1923
1924 >>> try:
1925 ... case.debug()
1926 ... except DocTestFailure, failure:
1927 ... pass
1928
1929 DocTestFailure objects provide access to the test:
1930
1931 >>> failure.test is test
1932 True
1933
1934 As well as to the example:
1935
1936 >>> failure.example.want
1937 '2\n'
1938
1939 and the actual output:
1940
1941 >>> failure.got
1942 '1\n'
1943
1944 """
1945
Edward Loper34fcb142004-08-09 02:45:41 +00001946 runner = DebugRunner(optionflags=self._dt_optionflags,
1947 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001948 runner.run(self._dt_test, out=nooutput)
Jim Fultona643b652004-07-14 19:06:50 +00001949
1950 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00001951 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00001952
1953 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00001954 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00001955 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
1956
1957 __str__ = __repr__
1958
1959 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00001960 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00001961
Tim Peters19397e52004-08-06 22:02:59 +00001962def nooutput(*args):
1963 pass
Jim Fultona643b652004-07-14 19:06:50 +00001964
Tim Peters19397e52004-08-06 22:02:59 +00001965def DocTestSuite(module=None, globs=None, extraglobs=None,
1966 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00001967 setUp=lambda: None, tearDown=lambda: None,
1968 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00001969 """
Tim Peters19397e52004-08-06 22:02:59 +00001970 Convert doctest tests for a mudule to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00001971
Tim Peters19397e52004-08-06 22:02:59 +00001972 This converts each documentation string in a module that
1973 contains doctest tests to a unittest test case. If any of the
1974 tests in a doc string fail, then the test case fails. An exception
1975 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00001976 (sometimes approximate) line number.
1977
Tim Peters19397e52004-08-06 22:02:59 +00001978 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00001979 can be either a module or a module name.
1980
1981 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00001982 """
Jim Fultona643b652004-07-14 19:06:50 +00001983
Tim Peters8485b562004-08-04 18:46:34 +00001984 if test_finder is None:
1985 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00001986
Tim Peters19397e52004-08-06 22:02:59 +00001987 module = _normalize_module(module)
1988 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
1989 if globs is None:
1990 globs = module.__dict__
1991 if not tests: # [XX] why do we want to do this?
1992 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00001993
1994 tests.sort()
1995 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00001996 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00001997 if len(test.examples) == 0:
1998 continue
Tim Peters8485b562004-08-04 18:46:34 +00001999 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002000 filename = module.__file__
2001 if filename.endswith(".pyc"):
2002 filename = filename[:-1]
2003 elif filename.endswith(".pyo"):
2004 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002005 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002006 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2007 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002008
2009 return suite
2010
2011class DocFileCase(DocTestCase):
2012
2013 def id(self):
2014 return '_'.join(self._dt_test.name.split('.'))
2015
2016 def __repr__(self):
2017 return self._dt_test.filename
2018 __str__ = __repr__
2019
2020 def format_failure(self, err):
2021 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2022 % (self._dt_test.name, self._dt_test.filename, err)
2023 )
2024
2025def DocFileTest(path, package=None, globs=None,
2026 setUp=None, tearDown=None,
2027 optionflags=0):
2028 package = _normalize_module(package)
2029 name = path.split('/')[-1]
2030 dir = os.path.split(package.__file__)[0]
2031 path = os.path.join(dir, *(path.split('/')))
2032 doc = open(path).read()
2033
2034 if globs is None:
2035 globs = {}
2036
Edward Lopera1ef6112004-08-09 16:14:41 +00002037 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002038
2039 return DocFileCase(test, optionflags, setUp, tearDown)
2040
2041def DocFileSuite(*paths, **kw):
2042 """Creates a suite of doctest files.
2043
2044 One or more text file paths are given as strings. These should
2045 use "/" characters to separate path segments. Paths are relative
2046 to the directory of the calling module, or relative to the package
2047 passed as a keyword argument.
2048
2049 A number of options may be provided as keyword arguments:
2050
2051 package
2052 The name of a Python package. Text-file paths will be
2053 interpreted relative to the directory containing this package.
2054 The package may be supplied as a package object or as a dotted
2055 package name.
2056
2057 setUp
2058 The name of a set-up function. This is called before running the
2059 tests in each file.
2060
2061 tearDown
2062 The name of a tear-down function. This is called after running the
2063 tests in each file.
2064
2065 globs
2066 A dictionary containing initial global variables for the tests.
2067 """
2068 suite = unittest.TestSuite()
2069
2070 # We do this here so that _normalize_module is called at the right
2071 # level. If it were called in DocFileTest, then this function
2072 # would be the caller and we might guess the package incorrectly.
2073 kw['package'] = _normalize_module(kw.get('package'))
2074
2075 for path in paths:
2076 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002077
Tim Petersdb3756d2003-06-29 05:30:48 +00002078 return suite
2079
Tim Peters8485b562004-08-04 18:46:34 +00002080######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002081## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002082######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002083
Tim Peters19397e52004-08-06 22:02:59 +00002084def script_from_examples(s):
2085 r"""Extract script from text with examples.
2086
2087 Converts text with examples to a Python script. Example input is
2088 converted to regular code. Example output and all other words
2089 are converted to comments:
2090
2091 >>> text = '''
2092 ... Here are examples of simple math.
2093 ...
2094 ... Python has super accurate integer addition
2095 ...
2096 ... >>> 2 + 2
2097 ... 5
2098 ...
2099 ... And very friendly error messages:
2100 ...
2101 ... >>> 1/0
2102 ... To Infinity
2103 ... And
2104 ... Beyond
2105 ...
2106 ... You can use logic if you want:
2107 ...
2108 ... >>> if 0:
2109 ... ... blah
2110 ... ... blah
2111 ... ...
2112 ...
2113 ... Ho hum
2114 ... '''
2115
2116 >>> print script_from_examples(text)
2117 # Here are examples of simple math.
2118 #
2119 # Python has super accurate integer addition
2120 #
2121 2 + 2
2122 # Expected:
2123 # 5
2124 #
2125 # And very friendly error messages:
2126 #
2127 1/0
2128 # Expected:
2129 # To Infinity
2130 # And
2131 # Beyond
2132 #
2133 # You can use logic if you want:
2134 #
2135 if 0:
2136 blah
2137 blah
2138 <BLANKLINE>
2139 #
2140 # Ho hum
2141 """
2142
Edward Lopera1ef6112004-08-09 16:14:41 +00002143 return DocTestParser().get_program(s)
Tim Peters19397e52004-08-06 22:02:59 +00002144
Tim Peters8485b562004-08-04 18:46:34 +00002145def _want_comment(example):
2146 """
Tim Peters19397e52004-08-06 22:02:59 +00002147 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002148 """
Jim Fultona643b652004-07-14 19:06:50 +00002149 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002150 want = example.want
2151 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002152 if want[-1] == '\n':
2153 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002154 want = "\n# ".join(want.split("\n"))
2155 want = "\n# Expected:\n# %s" % want
2156 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002157
2158def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002159 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002160
2161 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002162 test to be debugged and the name (within the module) of the object
2163 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002164 """
Tim Peters8485b562004-08-04 18:46:34 +00002165 module = _normalize_module(module)
2166 tests = DocTestFinder().find(module)
2167 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002168 if not test:
2169 raise ValueError(name, "not found in tests")
2170 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002171 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002172 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002173
Jim Fultona643b652004-07-14 19:06:50 +00002174def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002175 """Debug a single doctest docstring, in argument `src`'"""
2176 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002177 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002178
Jim Fultona643b652004-07-14 19:06:50 +00002179def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002180 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002181 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002182
Tim Petersdb3756d2003-06-29 05:30:48 +00002183 srcfilename = tempfile.mktemp("doctestdebug.py")
Tim Peters8485b562004-08-04 18:46:34 +00002184 f = open(srcfilename, 'w')
2185 f.write(src)
2186 f.close()
2187
Jim Fultona643b652004-07-14 19:06:50 +00002188 if globs:
2189 globs = globs.copy()
2190 else:
2191 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002192
Tim Peters8485b562004-08-04 18:46:34 +00002193 if pm:
2194 try:
2195 execfile(srcfilename, globs, globs)
2196 except:
2197 print sys.exc_info()[1]
2198 pdb.post_mortem(sys.exc_info()[2])
2199 else:
2200 # Note that %r is vital here. '%s' instead can, e.g., cause
2201 # backslashes to get treated as metacharacters on Windows.
2202 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002203
Jim Fultona643b652004-07-14 19:06:50 +00002204def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002205 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002206
2207 Provide the module (or dotted name of the module) containing the
2208 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002209 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002210 """
Tim Peters8485b562004-08-04 18:46:34 +00002211 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002212 testsrc = testsource(module, name)
2213 debug_script(testsrc, pm, module.__dict__)
2214
Tim Peters8485b562004-08-04 18:46:34 +00002215######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002216## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002217######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002218class _TestClass:
2219 """
2220 A pointless class, for sanity-checking of docstring testing.
2221
2222 Methods:
2223 square()
2224 get()
2225
2226 >>> _TestClass(13).get() + _TestClass(-12).get()
2227 1
2228 >>> hex(_TestClass(13).square().get())
2229 '0xa9'
2230 """
2231
2232 def __init__(self, val):
2233 """val -> _TestClass object with associated value val.
2234
2235 >>> t = _TestClass(123)
2236 >>> print t.get()
2237 123
2238 """
2239
2240 self.val = val
2241
2242 def square(self):
2243 """square() -> square TestClass's associated value
2244
2245 >>> _TestClass(13).square().get()
2246 169
2247 """
2248
2249 self.val = self.val ** 2
2250 return self
2251
2252 def get(self):
2253 """get() -> return TestClass's associated value.
2254
2255 >>> x = _TestClass(-42)
2256 >>> print x.get()
2257 -42
2258 """
2259
2260 return self.val
2261
2262__test__ = {"_TestClass": _TestClass,
2263 "string": r"""
2264 Example of a string object, searched as-is.
2265 >>> x = 1; y = 2
2266 >>> x + y, x * y
2267 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002268 """,
2269 "bool-int equivalence": r"""
2270 In 2.2, boolean expressions displayed
2271 0 or 1. By default, we still accept
2272 them. This can be disabled by passing
2273 DONT_ACCEPT_TRUE_FOR_1 to the new
2274 optionflags argument.
2275 >>> 4 == 4
2276 1
2277 >>> 4 == 4
2278 True
2279 >>> 4 > 4
2280 0
2281 >>> 4 > 4
2282 False
2283 """,
Tim Peters8485b562004-08-04 18:46:34 +00002284 "blank lines": r"""
2285 Blank lines can be marked with <BLANKLINE>:
2286 >>> print 'foo\n\nbar\n'
2287 foo
2288 <BLANKLINE>
2289 bar
2290 <BLANKLINE>
2291 """,
2292 }
2293# "ellipsis": r"""
2294# If the ellipsis flag is used, then '...' can be used to
2295# elide substrings in the desired output:
2296# >>> print range(1000)
2297# [0, 1, 2, ..., 999]
2298# """,
2299# "whitespace normalization": r"""
2300# If the whitespace normalization flag is used, then
2301# differences in whitespace are ignored.
2302# >>> print range(30)
2303# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2304# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2305# 27, 28, 29]
2306# """,
2307# }
2308
2309def test1(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002310>>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2311... "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002312>>> from doctest import Tester
2313>>> t = Tester(globs={'x': 42}, verbose=0)
2314>>> t.runstring(r'''
2315... >>> x = x * 2
2316... >>> print x
2317... 42
2318... ''', 'XYZ')
2319**********************************************************************
2320Failure in example: print x
2321from line #2 of XYZ
2322Expected: 42
2323Got: 84
2324(1, 2)
2325>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2326(0, 2)
2327>>> t.summarize()
2328**********************************************************************
23291 items had failures:
2330 1 of 2 in XYZ
2331***Test Failed*** 1 failures.
2332(1, 4)
2333>>> t.summarize(verbose=1)
23341 items passed all tests:
2335 2 tests in example2
2336**********************************************************************
23371 items had failures:
2338 1 of 2 in XYZ
23394 tests in 2 items.
23403 passed and 1 failed.
2341***Test Failed*** 1 failures.
2342(1, 4)
2343"""
2344
2345def test2(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002346 >>> warnings.filterwarnings("ignore", "class Tester",
2347 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002348 >>> t = Tester(globs={}, verbose=1)
2349 >>> test = r'''
2350 ... # just an example
2351 ... >>> x = 1 + 2
2352 ... >>> x
2353 ... 3
2354 ... '''
2355 >>> t.runstring(test, "Example")
2356 Running string Example
2357 Trying: x = 1 + 2
2358 Expecting: nothing
2359 ok
2360 Trying: x
2361 Expecting: 3
2362 ok
2363 0 of 2 examples failed in string Example
2364 (0, 2)
2365"""
2366def test3(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002367 >>> warnings.filterwarnings("ignore", "class Tester",
2368 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002369 >>> t = Tester(globs={}, verbose=0)
2370 >>> def _f():
2371 ... '''Trivial docstring example.
2372 ... >>> assert 2 == 2
2373 ... '''
2374 ... return 32
2375 ...
2376 >>> t.rundoc(_f) # expect 0 failures in 1 example
2377 (0, 1)
2378"""
2379def test4(): """
2380 >>> import new
2381 >>> m1 = new.module('_m1')
2382 >>> m2 = new.module('_m2')
2383 >>> test_data = \"""
2384 ... def _f():
2385 ... '''>>> assert 1 == 1
2386 ... '''
2387 ... def g():
2388 ... '''>>> assert 2 != 1
2389 ... '''
2390 ... class H:
2391 ... '''>>> assert 2 > 1
2392 ... '''
2393 ... def bar(self):
2394 ... '''>>> assert 1 < 2
2395 ... '''
2396 ... \"""
2397 >>> exec test_data in m1.__dict__
2398 >>> exec test_data in m2.__dict__
2399 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2400
2401 Tests that objects outside m1 are excluded:
2402
Tim Peters3ddd60a2004-08-08 02:43:33 +00002403 >>> warnings.filterwarnings("ignore", "class Tester",
2404 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002405 >>> t = Tester(globs={}, verbose=0)
Tim Petersf727c6c2004-08-08 01:48:59 +00002406 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Tim Peters8485b562004-08-04 18:46:34 +00002407 (0, 4)
2408
Tim Petersf727c6c2004-08-08 01:48:59 +00002409 Once more, not excluding stuff outside m1:
Tim Peters8485b562004-08-04 18:46:34 +00002410
2411 >>> t = Tester(globs={}, verbose=0)
2412 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2413 (0, 8)
2414
2415 The exclusion of objects from outside the designated module is
2416 meant to be invoked automagically by testmod.
2417
Tim Petersf727c6c2004-08-08 01:48:59 +00002418 >>> testmod(m1, verbose=False)
2419 (0, 4)
Tim Peters8485b562004-08-04 18:46:34 +00002420"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002421
2422def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002423 #import doctest
2424 #doctest.testmod(doctest, verbose=False,
2425 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2426 # UNIFIED_DIFF)
2427 #print '~'*70
2428 r = unittest.TextTestRunner()
2429 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002430
2431if __name__ == "__main__":
2432 _test()