blob: 34db93a4f2c173188668f0a7fd6ec9426897970a [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 Peters6ebe61f2003-06-27 20:48:05 +0000196# Option constants.
197DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
Tim Peters8485b562004-08-04 18:46:34 +0000198DONT_ACCEPT_BLANKLINE = 1 << 1
199NORMALIZE_WHITESPACE = 1 << 2
200ELLIPSIS = 1 << 3
201UNIFIED_DIFF = 1 << 4
202CONTEXT_DIFF = 1 << 5
Tim Peters6ebe61f2003-06-27 20:48:05 +0000203
Tim Peters8485b562004-08-04 18:46:34 +0000204OPTIONFLAGS_BY_NAME = {
205 'DONT_ACCEPT_TRUE_FOR_1': DONT_ACCEPT_TRUE_FOR_1,
206 'DONT_ACCEPT_BLANKLINE': DONT_ACCEPT_BLANKLINE,
207 'NORMALIZE_WHITESPACE': NORMALIZE_WHITESPACE,
208 'ELLIPSIS': ELLIPSIS,
209 'UNIFIED_DIFF': UNIFIED_DIFF,
210 'CONTEXT_DIFF': CONTEXT_DIFF,
211 }
Tim Peters8a7d2d52001-01-16 07:10:57 +0000212
Tim Peters8485b562004-08-04 18:46:34 +0000213# Special string markers for use in `want` strings:
214BLANKLINE_MARKER = '<BLANKLINE>'
215ELLIPSIS_MARKER = '...'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000216
Tim Peters19397e52004-08-06 22:02:59 +0000217
218# There are 4 basic classes:
219# - Example: a <source, want> pair, plus an intra-docstring line number.
220# - DocTest: a collection of examples, parsed from a docstring, plus
221# info about where the docstring came from (name, filename, lineno).
222# - DocTestFinder: extracts DocTests from a given object's docstring and
223# its contained objects' docstrings.
224# - DocTestRunner: runs DocTest cases, and accumulates statistics.
225#
226# So the basic picture is:
227#
228# list of:
229# +------+ +---------+ +-------+
230# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
231# +------+ +---------+ +-------+
232# | Example |
233# | ... |
234# | Example |
235# +---------+
236
Tim Peters8485b562004-08-04 18:46:34 +0000237######################################################################
238## Table of Contents
239######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000240# 1. Utility Functions
241# 2. Example & DocTest -- store test cases
242# 3. DocTest Parser -- extracts examples from strings
243# 4. DocTest Finder -- extracts test cases from objects
244# 5. DocTest Runner -- runs test cases
245# 6. Test Functions -- convenient wrappers for testing
246# 7. Tester Class -- for backwards compatibility
247# 8. Unittest Support
248# 9. Debugging Support
249# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000250
Tim Peters8485b562004-08-04 18:46:34 +0000251######################################################################
252## 1. Utility Functions
253######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000254
255def is_private(prefix, base):
256 """prefix, base -> true iff name prefix + "." + base is "private".
257
258 Prefix may be an empty string, and base does not contain a period.
259 Prefix is ignored (although functions you write conforming to this
260 protocol may make use of it).
261 Return true iff base begins with an (at least one) underscore, but
262 does not both begin and end with (at least) two underscores.
263
Tim Petersbafb1fe2004-08-08 01:52:57 +0000264 >>> warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
265 ... "doctest", 0)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000266 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000267 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000268 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000269 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000270 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000271 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000272 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000273 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000274 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000275 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000276 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000277 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000278 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000279 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000280 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000281 warnings.warn("is_private is deprecated; it wasn't useful; "
282 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000283 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000284 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
285
Tim Peters8485b562004-08-04 18:46:34 +0000286def _extract_future_flags(globs):
287 """
288 Return the compiler-flags associated with the future features that
289 have been imported into the given namespace (globs).
290 """
291 flags = 0
292 for fname in __future__.all_feature_names:
293 feature = globs.get(fname, None)
294 if feature is getattr(__future__, fname):
295 flags |= feature.compiler_flag
296 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000297
Tim Peters8485b562004-08-04 18:46:34 +0000298def _normalize_module(module, depth=2):
299 """
300 Return the module specified by `module`. In particular:
301 - If `module` is a module, then return module.
302 - If `module` is a string, then import and return the
303 module with that name.
304 - If `module` is None, then return the calling module.
305 The calling module is assumed to be the module of
306 the stack frame at the given depth in the call stack.
307 """
308 if inspect.ismodule(module):
309 return module
310 elif isinstance(module, (str, unicode)):
311 return __import__(module, globals(), locals(), ["*"])
312 elif module is None:
313 return sys.modules[sys._getframe(depth).f_globals['__name__']]
314 else:
315 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000316
Edward Lopera1ef6112004-08-09 16:14:41 +0000317def _tag_msg(tag, msg, indent=' '):
Tim Peters8485b562004-08-04 18:46:34 +0000318 """
319 Return a string that displays a tag-and-message pair nicely,
320 keeping the tag and its message on the same line when that
Edward Lopera1ef6112004-08-09 16:14:41 +0000321 makes sense. If the message is displayed on separate lines,
322 then `indent` is added to the beginning of each line.
Tim Peters8485b562004-08-04 18:46:34 +0000323 """
Tim Peters8485b562004-08-04 18:46:34 +0000324 # If the message doesn't end in a newline, then add one.
325 if msg[-1:] != '\n':
326 msg += '\n'
327 # If the message is short enough, and contains no internal
328 # newlines, then display it on the same line as the tag.
329 # Otherwise, display the tag on its own line.
330 if (len(tag) + len(msg) < 75 and
331 msg.find('\n', 0, len(msg)-1) == -1):
332 return '%s: %s' % (tag, msg)
333 else:
Edward Lopera1ef6112004-08-09 16:14:41 +0000334 msg = '\n'.join([indent+l for l in msg[:-1].split('\n')])
335 return '%s:\n%s\n' % (tag, msg)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000336
Tim Peters8485b562004-08-04 18:46:34 +0000337# Override some StringIO methods.
338class _SpoofOut(StringIO):
339 def getvalue(self):
340 result = StringIO.getvalue(self)
341 # If anything at all was written, make sure there's a trailing
342 # newline. There's no way for the expected output to indicate
343 # that a trailing newline is missing.
344 if result and not result.endswith("\n"):
345 result += "\n"
346 # Prevent softspace from screwing up the next test case, in
347 # case they used print with a trailing comma in an example.
348 if hasattr(self, "softspace"):
349 del self.softspace
350 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000351
Tim Peters8485b562004-08-04 18:46:34 +0000352 def truncate(self, size=None):
353 StringIO.truncate(self, size)
354 if hasattr(self, "softspace"):
355 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000356
Tim Peters8485b562004-08-04 18:46:34 +0000357######################################################################
358## 2. Example & DocTest
359######################################################################
360## - An "example" is a <source, want> pair, where "source" is a
361## fragment of source code, and "want" is the expected output for
362## "source." The Example class also includes information about
363## where the example was extracted from.
364##
Edward Lopera1ef6112004-08-09 16:14:41 +0000365## - A "doctest" is a collection of examples, typically extracted from
366## a string (such as an object's docstring). The DocTest class also
367## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000368
Tim Peters8485b562004-08-04 18:46:34 +0000369class Example:
370 """
371 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000372 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000373
Tim Petersbb431472004-08-09 03:51:46 +0000374 - source: A single Python statement, always ending with a newline.
375 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000376
Tim Petersbb431472004-08-09 03:51:46 +0000377 - want: The expected output from running the source code (either
378 from stdout, or a traceback in case of exception). `want` ends
379 with a newline unless it's empty, in which case it's an empty
380 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000381
Tim Petersbb431472004-08-09 03:51:46 +0000382 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000383 this Example where the Example begins. This line number is
384 zero-based, with respect to the beginning of the DocTest.
385 """
386 def __init__(self, source, want, lineno):
Tim Petersbb431472004-08-09 03:51:46 +0000387 # Normalize inputs.
388 if not source.endswith('\n'):
389 source += '\n'
390 if want and not want.endswith('\n'):
391 want += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000392 # Store properties.
393 self.source = source
394 self.want = want
395 self.lineno = lineno
Tim Peters8a7d2d52001-01-16 07:10:57 +0000396
Tim Peters8485b562004-08-04 18:46:34 +0000397class DocTest:
398 """
399 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000400 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000401
Tim Peters8485b562004-08-04 18:46:34 +0000402 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000403
Tim Peters8485b562004-08-04 18:46:34 +0000404 - globs: The namespace (aka globals) that the examples should
405 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000406
Tim Peters8485b562004-08-04 18:46:34 +0000407 - name: A name identifying the DocTest (typically, the name of
408 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000409
Tim Peters8485b562004-08-04 18:46:34 +0000410 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000411 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000412
Tim Peters8485b562004-08-04 18:46:34 +0000413 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000414 begins, or `None` if the line number is unavailable. This
415 line number is zero-based, with respect to the beginning of
416 the file.
417
418 - docstring: The string that the examples were extracted from,
419 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000420 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000421 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000422 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000423 Create a new DocTest containing the given examples. The
424 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000425 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000426 assert not isinstance(examples, basestring), \
427 "DocTest no longer accepts str; use DocTestParser instead"
428 self.examples = examples
429 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000430 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000431 self.name = name
432 self.filename = filename
433 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000434
435 def __repr__(self):
436 if len(self.examples) == 0:
437 examples = 'no examples'
438 elif len(self.examples) == 1:
439 examples = '1 example'
440 else:
441 examples = '%d examples' % len(self.examples)
442 return ('<DocTest %s from %s:%s (%s)>' %
443 (self.name, self.filename, self.lineno, examples))
444
445
446 # This lets us sort tests by name:
447 def __cmp__(self, other):
448 if not isinstance(other, DocTest):
449 return -1
450 return cmp((self.name, self.filename, self.lineno, id(self)),
451 (other.name, other.filename, other.lineno, id(other)))
452
453######################################################################
Edward Lopera1ef6112004-08-09 16:14:41 +0000454## 2. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000455######################################################################
456
Edward Lopera1ef6112004-08-09 16:14:41 +0000457class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000458 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000459 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000460 """
Edward Loper7c748462004-08-09 02:06:06 +0000461 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000462 # Source consists of a PS1 line followed by zero or more PS2 lines.
463 (?P<source>
464 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
465 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
466 \n?
467 # Want consists of any non-blank lines that do not start with PS1.
468 (?P<want> (?:(?![ ]*$) # Not a blank line
469 (?![ ]*>>>) # Not a line starting with PS1
470 .*$\n? # But any other line
471 )*)
472 ''', re.MULTILINE | re.VERBOSE)
473 _IS_BLANK_OR_COMMENT = re.compile('^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000474
Edward Lopera1ef6112004-08-09 16:14:41 +0000475 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000476 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000477 Extract all doctest examples from the given string, and
478 collect them into a `DocTest` object.
479
480 `globs`, `name`, `filename`, and `lineno` are attributes for
481 the new `DocTest` object. See the documentation for `DocTest`
482 for more information.
483 """
484 return DocTest(self.get_examples(string, name), globs,
485 name, filename, lineno, string)
486
487 def get_examples(self, string, name='<string>'):
488 """
489 Extract all doctest examples from the given string, and return
490 them as a list of `Example` objects. Line numbers are
491 0-based, because it's most common in doctests that nothing
492 interesting appears on the same line as opening triple-quote,
493 and so the first interesting line is called \"line 1\" then.
494
495 The optional argument `name` is a name identifying this
496 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000497
498 >>> text = '''
499 ... >>> x, y = 2, 3 # no output expected
500 ... >>> if 1:
501 ... ... print x
502 ... ... print y
503 ... 2
504 ... 3
505 ...
506 ... Some text.
507 ... >>> x+y
508 ... 5
509 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000510 >>> for x in DocTestParser().get_examples(text):
Edward Loper78b58f32004-08-09 02:56:02 +0000511 ... print (x.source, x.want, x.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000512 ('x, y = 2, 3 # no output expected\\n', '', 1)
Edward Loper7c748462004-08-09 02:06:06 +0000513 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
Tim Petersbb431472004-08-09 03:51:46 +0000514 ('x+y\\n', '5\\n', 9)
Edward Loper7c748462004-08-09 02:06:06 +0000515 """
516 examples = []
517 charno, lineno = 0, 0
518 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000519 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000520 # Update lineno (lines before this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000521 lineno += string.count('\n', charno, m.start())
Edward Loper7c748462004-08-09 02:06:06 +0000522
523 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000524 (source, want) = self._parse_example(m, name, lineno)
Tim Petersd40a92b2004-08-09 03:28:45 +0000525 if self._IS_BLANK_OR_COMMENT(source):
Edward Loper7c748462004-08-09 02:06:06 +0000526 continue
Edward Loper78b58f32004-08-09 02:56:02 +0000527 examples.append( Example(source, want, lineno) )
Edward Loper7c748462004-08-09 02:06:06 +0000528
529 # Update lineno (lines inside this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000530 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000531 # Update charno.
532 charno = m.end()
533 return examples
534
Edward Lopera1ef6112004-08-09 16:14:41 +0000535 def get_program(self, string, name="<string>"):
Edward Loper7c748462004-08-09 02:06:06 +0000536 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000537 Return an executable program from the given string, as a string.
Edward Loper7c748462004-08-09 02:06:06 +0000538
539 The format of this isn't rigidly defined. In general, doctest
540 examples become the executable statements in the result, and
541 their expected outputs become comments, preceded by an \"#Expected:\"
542 comment. Everything else (text, comments, everything not part of
543 a doctest test) is also placed in comments.
544
Edward Lopera1ef6112004-08-09 16:14:41 +0000545 The optional argument `name` is a name identifying this
546 string, and is only used for error messages.
547
Edward Loper7c748462004-08-09 02:06:06 +0000548 >>> text = '''
549 ... >>> x, y = 2, 3 # no output expected
550 ... >>> if 1:
551 ... ... print x
552 ... ... print y
553 ... 2
554 ... 3
555 ...
556 ... Some text.
557 ... >>> x+y
558 ... 5
559 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000560 >>> print DocTestParser().get_program(text)
Edward Loper7c748462004-08-09 02:06:06 +0000561 x, y = 2, 3 # no output expected
562 if 1:
563 print x
564 print y
565 # Expected:
566 # 2
567 # 3
568 #
569 # Some text.
570 x+y
571 # Expected:
572 # 5
573 """
574 output = []
575 charnum, lineno = 0, 0
576 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000577 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000578 # Add any text before this example, as a comment.
579 if m.start() > charnum:
Edward Lopera1ef6112004-08-09 16:14:41 +0000580 lines = string[charnum:m.start()-1].split('\n')
Edward Loper7c748462004-08-09 02:06:06 +0000581 output.extend([self._comment_line(l) for l in lines])
582 lineno += len(lines)
583
584 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000585 (source, want) = self._parse_example(m, name, lineno, False)
Edward Loper7c748462004-08-09 02:06:06 +0000586 # Display the source
587 output.append(source)
588 # Display the expected output, if any
589 if want:
590 output.append('# Expected:')
591 output.extend(['# '+l for l in want.split('\n')])
592
593 # Update the line number & char number.
Edward Lopera1ef6112004-08-09 16:14:41 +0000594 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000595 charnum = m.end()
596 # Add any remaining text, as comments.
597 output.extend([self._comment_line(l)
Edward Lopera1ef6112004-08-09 16:14:41 +0000598 for l in string[charnum:].split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000599 # Trim junk on both ends.
600 while output and output[-1] == '#':
601 output.pop()
602 while output and output[0] == '#':
603 output.pop(0)
604 # Combine the output, and return it.
605 return '\n'.join(output)
606
Edward Lopera1ef6112004-08-09 16:14:41 +0000607 def _parse_example(self, m, name, lineno, add_newlines=True):
Edward Loper7c748462004-08-09 02:06:06 +0000608 # Get the example's indentation level.
609 indent = len(m.group('indent'))
610
611 # Divide source into lines; check that they're properly
612 # indented; and then strip their indentation & prompts.
613 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000614 self._check_prompt_blank(source_lines, indent, name, lineno)
615 self._check_prefix(source_lines[1:], ' '*indent+'.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000616 source = '\n'.join([sl[indent+4:] for sl in source_lines])
617 if len(source_lines) > 1 and add_newlines:
618 source += '\n'
619
620 # Divide want into lines; check that it's properly
621 # indented; and then strip the indentation.
622 want_lines = m.group('want').rstrip().split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000623 self._check_prefix(want_lines, ' '*indent, name,
Edward Loper7c748462004-08-09 02:06:06 +0000624 lineno+len(source_lines))
625 want = '\n'.join([wl[indent:] for wl in want_lines])
626 if len(want) > 0 and add_newlines:
627 want += '\n'
628
629 return source, want
630
631 def _comment_line(self, line):
632 line = line.rstrip()
Tim Petersdd0e4752004-08-09 03:31:56 +0000633 if line:
634 return '# '+line
635 else:
636 return '#'
Edward Loper7c748462004-08-09 02:06:06 +0000637
Edward Lopera1ef6112004-08-09 16:14:41 +0000638 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000639 for i, line in enumerate(lines):
640 if len(line) >= indent+4 and line[indent+3] != ' ':
641 raise ValueError('line %r of the docstring for %s '
642 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000643 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000644 line[indent:indent+3], line))
645
Edward Lopera1ef6112004-08-09 16:14:41 +0000646 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000647 for i, line in enumerate(lines):
648 if line and not line.startswith(prefix):
649 raise ValueError('line %r of the docstring for %s has '
650 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000651 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000652
653
654######################################################################
655## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000656######################################################################
657
658class DocTestFinder:
659 """
660 A class used to extract the DocTests that are relevant to a given
661 object, from its docstring and the docstrings of its contained
662 objects. Doctests can currently be extracted from the following
663 object types: modules, functions, classes, methods, staticmethods,
664 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000665 """
666
Edward Lopera1ef6112004-08-09 16:14:41 +0000667 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000668 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000669 """
670 Create a new doctest finder.
671
Edward Lopera1ef6112004-08-09 16:14:41 +0000672 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000673 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000674 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000675 signature for this factory function should match the signature
676 of the DocTest constructor.
677
Tim Peters8485b562004-08-04 18:46:34 +0000678 If the optional argument `recurse` is false, then `find` will
679 only examine the given object, and not any contained objects.
680 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000681 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000682 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000683 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000684 # _namefilter is undocumented, and exists only for temporary backward-
685 # compatibility support of testmod's deprecated isprivate mess.
686 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000687
688 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000689 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000690 """
691 Return a list of the DocTests that are defined by the given
692 object's docstring, or by any of its contained objects'
693 docstrings.
694
695 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000696 the given object. If the module is not specified or is None, then
697 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000698 correct module. The object's module is used:
699
700 - As a default namespace, if `globs` is not specified.
701 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000702 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000703 - To find the name of the file containing the object.
704 - To help find the line number of the object within its
705 file.
706
Tim Petersf3f57472004-08-08 06:11:48 +0000707 Contained objects whose module does not match `module` are ignored.
708
709 If `module` is False, no attempt to find the module will be made.
710 This is obscure, of use mostly in tests: if `module` is False, or
711 is None but cannot be found automatically, then all objects are
712 considered to belong to the (non-existent) module, so all contained
713 objects will (recursively) be searched for doctests.
714
Tim Peters8485b562004-08-04 18:46:34 +0000715 The globals for each DocTest is formed by combining `globs`
716 and `extraglobs` (bindings in `extraglobs` override bindings
717 in `globs`). A new copy of the globals dictionary is created
718 for each DocTest. If `globs` is not specified, then it
719 defaults to the module's `__dict__`, if specified, or {}
720 otherwise. If `extraglobs` is not specified, then it defaults
721 to {}.
722
Tim Peters8485b562004-08-04 18:46:34 +0000723 """
724 # If name was not specified, then extract it from the object.
725 if name is None:
726 name = getattr(obj, '__name__', None)
727 if name is None:
728 raise ValueError("DocTestFinder.find: name must be given "
729 "when obj.__name__ doesn't exist: %r" %
730 (type(obj),))
731
732 # Find the module that contains the given object (if obj is
733 # a module, then module=obj.). Note: this may fail, in which
734 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000735 if module is False:
736 module = None
737 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000738 module = inspect.getmodule(obj)
739
740 # Read the module's source code. This is used by
741 # DocTestFinder._find_lineno to find the line number for a
742 # given object's docstring.
743 try:
744 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
745 source_lines = linecache.getlines(file)
746 if not source_lines:
747 source_lines = None
748 except TypeError:
749 source_lines = None
750
751 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000752 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000753 if module is None:
754 globs = {}
755 else:
756 globs = module.__dict__.copy()
757 else:
758 globs = globs.copy()
759 if extraglobs is not None:
760 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000761
Tim Peters8485b562004-08-04 18:46:34 +0000762 # Recursively expore `obj`, extracting DocTests.
763 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000764 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000765 return tests
766
767 def _filter(self, obj, prefix, base):
768 """
769 Return true if the given object should not be examined.
770 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000771 return (self._namefilter is not None and
772 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000773
774 def _from_module(self, module, object):
775 """
776 Return true if the given object is defined in the given
777 module.
778 """
779 if module is None:
780 return True
781 elif inspect.isfunction(object):
782 return module.__dict__ is object.func_globals
783 elif inspect.isclass(object):
784 return module.__name__ == object.__module__
785 elif inspect.getmodule(object) is not None:
786 return module is inspect.getmodule(object)
787 elif hasattr(object, '__module__'):
788 return module.__name__ == object.__module__
789 elif isinstance(object, property):
790 return True # [XX] no way not be sure.
791 else:
792 raise ValueError("object must be a class or function")
793
Tim Petersf3f57472004-08-08 06:11:48 +0000794 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000795 """
796 Find tests for the given object and any contained objects, and
797 add them to `tests`.
798 """
799 if self._verbose:
800 print 'Finding tests in %s' % name
801
802 # If we've already processed this object, then ignore it.
803 if id(obj) in seen:
804 return
805 seen[id(obj)] = 1
806
807 # Find a test for this object, and add it to the list of tests.
808 test = self._get_test(obj, name, module, globs, source_lines)
809 if test is not None:
810 tests.append(test)
811
812 # Look for tests in a module's contained objects.
813 if inspect.ismodule(obj) and self._recurse:
814 for valname, val in obj.__dict__.items():
815 # Check if this contained object should be ignored.
816 if self._filter(val, name, valname):
817 continue
818 valname = '%s.%s' % (name, valname)
819 # Recurse to functions & classes.
820 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000821 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000822 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000823 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000824
825 # Look for tests in a module's __test__ dictionary.
826 if inspect.ismodule(obj) and self._recurse:
827 for valname, val in getattr(obj, '__test__', {}).items():
828 if not isinstance(valname, basestring):
829 raise ValueError("DocTestFinder.find: __test__ keys "
830 "must be strings: %r" %
831 (type(valname),))
832 if not (inspect.isfunction(val) or inspect.isclass(val) or
833 inspect.ismethod(val) or inspect.ismodule(val) or
834 isinstance(val, basestring)):
835 raise ValueError("DocTestFinder.find: __test__ values "
836 "must be strings, functions, methods, "
837 "classes, or modules: %r" %
838 (type(val),))
839 valname = '%s.%s' % (name, valname)
840 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000841 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000842
843 # Look for tests in a class's contained objects.
844 if inspect.isclass(obj) and self._recurse:
845 for valname, val in obj.__dict__.items():
846 # Check if this contained object should be ignored.
847 if self._filter(val, name, valname):
848 continue
849 # Special handling for staticmethod/classmethod.
850 if isinstance(val, staticmethod):
851 val = getattr(obj, valname)
852 if isinstance(val, classmethod):
853 val = getattr(obj, valname).im_func
854
855 # Recurse to methods, properties, and nested classes.
856 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +0000857 isinstance(val, property)) and
858 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000859 valname = '%s.%s' % (name, valname)
860 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000861 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000862
863 def _get_test(self, obj, name, module, globs, source_lines):
864 """
865 Return a DocTest for the given object, if it defines a docstring;
866 otherwise, return None.
867 """
868 # Extract the object's docstring. If it doesn't have one,
869 # then return None (no test for this object).
870 if isinstance(obj, basestring):
871 docstring = obj
872 else:
873 try:
874 if obj.__doc__ is None:
875 return None
876 docstring = str(obj.__doc__)
877 except (TypeError, AttributeError):
878 return None
879
880 # Don't bother if the docstring is empty.
881 if not docstring:
882 return None
883
884 # Find the docstring's location in the file.
885 lineno = self._find_lineno(obj, source_lines)
886
887 # Return a DocTest for this object.
888 if module is None:
889 filename = None
890 else:
891 filename = getattr(module, '__file__', module.__name__)
Edward Lopera1ef6112004-08-09 16:14:41 +0000892 return self._parser.get_doctest(docstring, globs, name,
893 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +0000894
895 def _find_lineno(self, obj, source_lines):
896 """
897 Return a line number of the given object's docstring. Note:
898 this method assumes that the object has a docstring.
899 """
900 lineno = None
901
902 # Find the line number for modules.
903 if inspect.ismodule(obj):
904 lineno = 0
905
906 # Find the line number for classes.
907 # Note: this could be fooled if a class is defined multiple
908 # times in a single file.
909 if inspect.isclass(obj):
910 if source_lines is None:
911 return None
912 pat = re.compile(r'^\s*class\s*%s\b' %
913 getattr(obj, '__name__', '-'))
914 for i, line in enumerate(source_lines):
915 if pat.match(line):
916 lineno = i
917 break
918
919 # Find the line number for functions & methods.
920 if inspect.ismethod(obj): obj = obj.im_func
921 if inspect.isfunction(obj): obj = obj.func_code
922 if inspect.istraceback(obj): obj = obj.tb_frame
923 if inspect.isframe(obj): obj = obj.f_code
924 if inspect.iscode(obj):
925 lineno = getattr(obj, 'co_firstlineno', None)-1
926
927 # Find the line number where the docstring starts. Assume
928 # that it's the first line that begins with a quote mark.
929 # Note: this could be fooled by a multiline function
930 # signature, where a continuation line begins with a quote
931 # mark.
932 if lineno is not None:
933 if source_lines is None:
934 return lineno+1
935 pat = re.compile('(^|.*:)\s*\w*("|\')')
936 for lineno in range(lineno, len(source_lines)):
937 if pat.match(source_lines[lineno]):
938 return lineno
939
940 # We couldn't find the line number.
941 return None
942
943######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000944## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +0000945######################################################################
946
Tim Peters8485b562004-08-04 18:46:34 +0000947class DocTestRunner:
948 """
949 A class used to run DocTest test cases, and accumulate statistics.
950 The `run` method is used to process a single DocTest case. It
951 returns a tuple `(f, t)`, where `t` is the number of test cases
952 tried, and `f` is the number of test cases that failed.
953
954 >>> tests = DocTestFinder().find(_TestClass)
955 >>> runner = DocTestRunner(verbose=False)
956 >>> for test in tests:
957 ... print runner.run(test)
958 (0, 2)
959 (0, 1)
960 (0, 2)
961 (0, 2)
962
963 The `summarize` method prints a summary of all the test cases that
964 have been run by the runner, and returns an aggregated `(f, t)`
965 tuple:
966
967 >>> runner.summarize(verbose=1)
968 4 items passed all tests:
969 2 tests in _TestClass
970 2 tests in _TestClass.__init__
971 2 tests in _TestClass.get
972 1 tests in _TestClass.square
973 7 tests in 4 items.
974 7 passed and 0 failed.
975 Test passed.
976 (0, 7)
977
978 The aggregated number of tried examples and failed examples is
979 also available via the `tries` and `failures` attributes:
980
981 >>> runner.tries
982 7
983 >>> runner.failures
984 0
985
986 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +0000987 by an `OutputChecker`. This comparison may be customized with a
988 number of option flags; see the documentation for `testmod` for
989 more information. If the option flags are insufficient, then the
990 comparison may also be customized by passing a subclass of
991 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +0000992
993 The test runner's display output can be controlled in two ways.
994 First, an output function (`out) can be passed to
995 `TestRunner.run`; this function will be called with strings that
996 should be displayed. It defaults to `sys.stdout.write`. If
997 capturing the output is not sufficient, then the display output
998 can be also customized by subclassing DocTestRunner, and
999 overriding the methods `report_start`, `report_success`,
1000 `report_unexpected_exception`, and `report_failure`.
1001 """
1002 # This divider string is used to separate failure messages, and to
1003 # separate sections of the summary.
1004 DIVIDER = "*" * 70
1005
Edward Loper34fcb142004-08-09 02:45:41 +00001006 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001007 """
1008 Create a new test runner.
1009
Edward Loper34fcb142004-08-09 02:45:41 +00001010 Optional keyword arg `checker` is the `OutputChecker` that
1011 should be used to compare the expected outputs and actual
1012 outputs of doctest examples.
1013
Tim Peters8485b562004-08-04 18:46:34 +00001014 Optional keyword arg 'verbose' prints lots of stuff if true,
1015 only failures if false; by default, it's true iff '-v' is in
1016 sys.argv.
1017
1018 Optional argument `optionflags` can be used to control how the
1019 test runner compares expected output to actual output, and how
1020 it displays failures. See the documentation for `testmod` for
1021 more information.
1022 """
Edward Loper34fcb142004-08-09 02:45:41 +00001023 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001024 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001025 verbose = '-v' in sys.argv
1026 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001027 self.optionflags = optionflags
1028
Tim Peters8485b562004-08-04 18:46:34 +00001029 # Keep track of the examples we've run.
1030 self.tries = 0
1031 self.failures = 0
1032 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001033
Tim Peters8485b562004-08-04 18:46:34 +00001034 # Create a fake output target for capturing doctest output.
1035 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001036
Tim Peters8485b562004-08-04 18:46:34 +00001037 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001038 # Reporting methods
1039 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001040
Tim Peters8485b562004-08-04 18:46:34 +00001041 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001042 """
Tim Peters8485b562004-08-04 18:46:34 +00001043 Report that the test runner is about to process the given
1044 example. (Only displays a message if verbose=True)
1045 """
1046 if self._verbose:
1047 out(_tag_msg("Trying", example.source) +
1048 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001049
Tim Peters8485b562004-08-04 18:46:34 +00001050 def report_success(self, out, test, example, got):
1051 """
1052 Report that the given example ran successfully. (Only
1053 displays a message if verbose=True)
1054 """
1055 if self._verbose:
1056 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001057
Tim Peters8485b562004-08-04 18:46:34 +00001058 def report_failure(self, out, test, example, got):
1059 """
1060 Report that the given example failed.
1061 """
1062 # Print an error message.
1063 out(self.__failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001064 self._checker.output_difference(example.want, got,
1065 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001066
Tim Peters8485b562004-08-04 18:46:34 +00001067 def report_unexpected_exception(self, out, test, example, exc_info):
1068 """
1069 Report that the given example raised an unexpected exception.
1070 """
1071 # Get a traceback message.
1072 excout = StringIO()
1073 exc_type, exc_val, exc_tb = exc_info
1074 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
1075 exception_tb = excout.getvalue()
1076 # Print an error message.
1077 out(self.__failure_header(test, example) +
1078 _tag_msg("Exception raised", exception_tb))
Tim Peters7402f792001-10-02 03:53:41 +00001079
Tim Peters8485b562004-08-04 18:46:34 +00001080 def __failure_header(self, test, example):
1081 s = (self.DIVIDER + "\n" +
1082 _tag_msg("Failure in example", example.source))
1083 if test.filename is None:
1084 # [XX] I'm not putting +1 here, to give the same output
1085 # as the old version. But I think it *should* go here.
1086 return s + ("from line #%s of %s\n" %
1087 (example.lineno, test.name))
1088 elif test.lineno is None:
1089 return s + ("from line #%s of %s in %s\n" %
1090 (example.lineno+1, test.name, test.filename))
1091 else:
1092 lineno = test.lineno+example.lineno+1
1093 return s + ("from line #%s of %s (%s)\n" %
1094 (lineno, test.filename, test.name))
Tim Peters7402f792001-10-02 03:53:41 +00001095
Tim Peters8485b562004-08-04 18:46:34 +00001096 #/////////////////////////////////////////////////////////////////
1097 # DocTest Running
1098 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001099
Tim Peters8485b562004-08-04 18:46:34 +00001100 # A regular expression for handling `want` strings that contain
1101 # expected exceptions. It divides `want` into two pieces: the
1102 # pre-exception output (`out`) and the exception message (`exc`),
1103 # as generated by traceback.format_exception_only(). (I assume
1104 # that the exception_only message is the first non-indented line
1105 # starting with word characters after the "Traceback ...".)
1106 _EXCEPTION_RE = re.compile(('^(?P<out>.*)'
1107 '^(?P<hdr>Traceback \((?:%s|%s)\):)\s*$.*?'
1108 '^(?P<exc>\w+.*)') %
1109 ('most recent call last', 'innermost last'),
1110 re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001111
Tim Peters8485b562004-08-04 18:46:34 +00001112 _OPTION_DIRECTIVE_RE = re.compile('\s*doctest:\s*(?P<flags>[^#\n]*)')
Tim Peters7402f792001-10-02 03:53:41 +00001113
Tim Peters8485b562004-08-04 18:46:34 +00001114 def __handle_directive(self, example):
1115 """
1116 Check if the given example is actually a directive to doctest
1117 (to turn an optionflag on or off); and if it is, then handle
1118 the directive.
Tim Peters7402f792001-10-02 03:53:41 +00001119
Tim Peters8485b562004-08-04 18:46:34 +00001120 Return true iff the example is actually a directive (and so
1121 should not be executed).
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001122
Tim Peters8a7d2d52001-01-16 07:10:57 +00001123 """
Tim Peters8485b562004-08-04 18:46:34 +00001124 m = self._OPTION_DIRECTIVE_RE.match(example.source)
1125 if m is None:
1126 return False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001127
Tim Peters8485b562004-08-04 18:46:34 +00001128 for flag in m.group('flags').upper().split():
1129 if (flag[:1] not in '+-' or
1130 flag[1:] not in OPTIONFLAGS_BY_NAME):
1131 raise ValueError('Bad doctest option directive: '+flag)
1132 if flag[0] == '+':
1133 self.optionflags |= OPTIONFLAGS_BY_NAME[flag[1:]]
1134 else:
1135 self.optionflags &= ~OPTIONFLAGS_BY_NAME[flag[1:]]
1136 return True
Tim Peters8a7d2d52001-01-16 07:10:57 +00001137
Tim Peters8485b562004-08-04 18:46:34 +00001138 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001139 """
Tim Peters8485b562004-08-04 18:46:34 +00001140 Run the examples in `test`. Write the outcome of each example
1141 with one of the `DocTestRunner.report_*` methods, using the
1142 writer function `out`. `compileflags` is the set of compiler
1143 flags that should be used to execute examples. Return a tuple
1144 `(f, t)`, where `t` is the number of examples tried, and `f`
1145 is the number of examples that failed. The examples are run
1146 in the namespace `test.globs`.
1147 """
1148 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001149 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001150
1151 # Save the option flags (since option directives can be used
1152 # to modify them).
1153 original_optionflags = self.optionflags
1154
1155 # Process each example.
1156 for example in test.examples:
1157 # Check if it's an option directive. If it is, then handle
1158 # it, and go on to the next example.
1159 if self.__handle_directive(example):
1160 continue
1161
1162 # Record that we started this example.
1163 tries += 1
1164 self.report_start(out, test, example)
1165
1166 # Run the example in the given context (globs), and record
1167 # any exception that gets raised. (But don't intercept
1168 # keyboard interrupts.)
1169 try:
Tim Peters208ca702004-08-09 04:12:36 +00001170 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001171 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001172 compileflags, 1) in test.globs
1173 exception = None
1174 except KeyboardInterrupt:
1175 raise
1176 except:
1177 exception = sys.exc_info()
1178
Tim Peters208ca702004-08-09 04:12:36 +00001179 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001180 self._fakeout.truncate(0)
1181
1182 # If the example executed without raising any exceptions,
1183 # then verify its output and report its outcome.
1184 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001185 if self._checker.check_output(example.want, got,
1186 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001187 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001188 else:
Tim Peters8485b562004-08-04 18:46:34 +00001189 self.report_failure(out, test, example, got)
1190 failures += 1
1191
1192 # If the example raised an exception, then check if it was
1193 # expected.
1194 else:
1195 exc_info = sys.exc_info()
1196 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1197
1198 # Search the `want` string for an exception. If we don't
1199 # find one, then report an unexpected exception.
1200 m = self._EXCEPTION_RE.match(example.want)
1201 if m is None:
1202 self.report_unexpected_exception(out, test, example,
1203 exc_info)
1204 failures += 1
1205 else:
1206 exc_hdr = m.group('hdr')+'\n' # Exception header
1207 # The test passes iff the pre-exception output and
1208 # the exception description match the values given
1209 # in `want`.
Edward Loper34fcb142004-08-09 02:45:41 +00001210 if (self._checker.check_output(m.group('out'), got,
1211 self.optionflags) and
1212 self._checker.check_output(m.group('exc'), exc_msg,
1213 self.optionflags)):
Tim Peters8485b562004-08-04 18:46:34 +00001214 # Is +exc_msg the right thing here??
1215 self.report_success(out, test, example,
1216 got+exc_hdr+exc_msg)
1217 else:
1218 self.report_failure(out, test, example,
1219 got+exc_hdr+exc_msg)
1220 failures += 1
1221
1222 # Restore the option flags (in case they were modified)
1223 self.optionflags = original_optionflags
1224
1225 # Record and return the number of failures and tries.
1226 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001227 return failures, tries
1228
Tim Peters8485b562004-08-04 18:46:34 +00001229 def __record_outcome(self, test, f, t):
1230 """
1231 Record the fact that the given DocTest (`test`) generated `f`
1232 failures out of `t` tried examples.
1233 """
1234 f2, t2 = self._name2ft.get(test.name, (0,0))
1235 self._name2ft[test.name] = (f+f2, t+t2)
1236 self.failures += f
1237 self.tries += t
1238
1239 def run(self, test, compileflags=None, out=None, clear_globs=True):
1240 """
1241 Run the examples in `test`, and display the results using the
1242 writer function `out`.
1243
1244 The examples are run in the namespace `test.globs`. If
1245 `clear_globs` is true (the default), then this namespace will
1246 be cleared after the test runs, to help with garbage
1247 collection. If you would like to examine the namespace after
1248 the test completes, then use `clear_globs=False`.
1249
1250 `compileflags` gives the set of flags that should be used by
1251 the Python compiler when running the examples. If not
1252 specified, then it will default to the set of future-import
1253 flags that apply to `globs`.
1254
1255 The output of each example is checked using
1256 `DocTestRunner.check_output`, and the results are formatted by
1257 the `DocTestRunner.report_*` methods.
1258 """
1259 if compileflags is None:
1260 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001261
Tim Peters8485b562004-08-04 18:46:34 +00001262 if out is None:
Edward Lopera1ef6112004-08-09 16:14:41 +00001263 out = sys.stdout.write
1264 saveout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001265
Edward Lopera1ef6112004-08-09 16:14:41 +00001266 # Note that don't save away the previous pdb.set_trace. Rather,
1267 # we safe pdb.set_trace on import (see import section above).
1268 # We then call and restore that original cersion. We do it this
1269 # way to make this feature testable. If we kept and called the
1270 # previous version, we'd end up restoring the original stdout,
1271 # which is not what we want.
Jim Fulton356fd192004-08-09 11:34:47 +00001272 def set_trace():
Edward Lopera1ef6112004-08-09 16:14:41 +00001273 sys.stdout = saveout
Jim Fulton356fd192004-08-09 11:34:47 +00001274 real_pdb_set_trace()
1275
Tim Peters8485b562004-08-04 18:46:34 +00001276 try:
Edward Lopera1ef6112004-08-09 16:14:41 +00001277 sys.stdout = self._fakeout
1278 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001279 return self.__run(test, compileflags, out)
1280 finally:
Edward Lopera1ef6112004-08-09 16:14:41 +00001281 sys.stdout = saveout
1282 pdb.set_trace = real_pdb_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001283 if clear_globs:
1284 test.globs.clear()
1285
1286 #/////////////////////////////////////////////////////////////////
1287 # Summarization
1288 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001289 def summarize(self, verbose=None):
1290 """
Tim Peters8485b562004-08-04 18:46:34 +00001291 Print a summary of all the test cases that have been run by
1292 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1293 the total number of failed examples, and `t` is the total
1294 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001295
Tim Peters8485b562004-08-04 18:46:34 +00001296 The optional `verbose` argument controls how detailed the
1297 summary is. If the verbosity is not specified, then the
1298 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001299 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001300 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001301 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001302 notests = []
1303 passed = []
1304 failed = []
1305 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001306 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001307 name, (f, t) = x
1308 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001309 totalt += t
1310 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001311 if t == 0:
1312 notests.append(name)
1313 elif f == 0:
1314 passed.append( (name, t) )
1315 else:
1316 failed.append(x)
1317 if verbose:
1318 if notests:
1319 print len(notests), "items had no tests:"
1320 notests.sort()
1321 for thing in notests:
1322 print " ", thing
1323 if passed:
1324 print len(passed), "items passed all tests:"
1325 passed.sort()
1326 for thing, count in passed:
1327 print " %3d tests in %s" % (count, thing)
1328 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001329 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001330 print len(failed), "items had failures:"
1331 failed.sort()
1332 for thing, (f, t) in failed:
1333 print " %3d of %3d in %s" % (f, t, thing)
1334 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001335 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001336 print totalt - totalf, "passed and", totalf, "failed."
1337 if totalf:
1338 print "***Test Failed***", totalf, "failures."
1339 elif verbose:
1340 print "Test passed."
1341 return totalf, totalt
1342
Edward Loper34fcb142004-08-09 02:45:41 +00001343class OutputChecker:
1344 """
1345 A class used to check the whether the actual output from a doctest
1346 example matches the expected output. `OutputChecker` defines two
1347 methods: `check_output`, which compares a given pair of outputs,
1348 and returns true if they match; and `output_difference`, which
1349 returns a string describing the differences between two outputs.
1350 """
1351 def check_output(self, want, got, optionflags):
1352 """
1353 Return True iff the actual output (`got`) matches the expected
1354 output (`want`). These strings are always considered to match
1355 if they are identical; but depending on what option flags the
1356 test runner is using, several non-exact match types are also
1357 possible. See the documentation for `TestRunner` for more
1358 information about option flags.
1359 """
1360 # Handle the common case first, for efficiency:
1361 # if they're string-identical, always return true.
1362 if got == want:
1363 return True
1364
1365 # The values True and False replaced 1 and 0 as the return
1366 # value for boolean comparisons in Python 2.3.
1367 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1368 if (got,want) == ("True\n", "1\n"):
1369 return True
1370 if (got,want) == ("False\n", "0\n"):
1371 return True
1372
1373 # <BLANKLINE> can be used as a special sequence to signify a
1374 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1375 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1376 # Replace <BLANKLINE> in want with a blank line.
1377 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1378 '', want)
1379 # If a line in got contains only spaces, then remove the
1380 # spaces.
1381 got = re.sub('(?m)^\s*?$', '', got)
1382 if got == want:
1383 return True
1384
1385 # This flag causes doctest to ignore any differences in the
1386 # contents of whitespace strings. Note that this can be used
1387 # in conjunction with the ELLISPIS flag.
1388 if (optionflags & NORMALIZE_WHITESPACE):
1389 got = ' '.join(got.split())
1390 want = ' '.join(want.split())
1391 if got == want:
1392 return True
1393
1394 # The ELLIPSIS flag says to let the sequence "..." in `want`
1395 # match any substring in `got`. We implement this by
1396 # transforming `want` into a regular expression.
1397 if (optionflags & ELLIPSIS):
1398 # Escape any special regexp characters
1399 want_re = re.escape(want)
1400 # Replace ellipsis markers ('...') with .*
1401 want_re = want_re.replace(re.escape(ELLIPSIS_MARKER), '.*')
1402 # Require that it matches the entire string; and set the
1403 # re.DOTALL flag (with '(?s)').
1404 want_re = '(?s)^%s$' % want_re
1405 # Check if the `want_re` regexp matches got.
1406 if re.match(want_re, got):
1407 return True
1408
1409 # We didn't find any match; return false.
1410 return False
1411
1412 def output_difference(self, want, got, optionflags):
1413 """
1414 Return a string describing the differences between the
1415 expected output (`want`) and the actual output (`got`).
1416 """
1417 # If <BLANKLINE>s are being used, then replace <BLANKLINE>
1418 # with blank lines in the expected output string.
1419 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1420 want = re.sub('(?m)^%s$' % re.escape(BLANKLINE_MARKER), '', want)
1421
1422 # Check if we should use diff. Don't use diff if the actual
1423 # or expected outputs are too short, or if the expected output
1424 # contains an ellipsis marker.
1425 if ((optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and
1426 want.count('\n') > 2 and got.count('\n') > 2 and
1427 not (optionflags & ELLIPSIS and '...' in want)):
1428 # Split want & got into lines.
1429 want_lines = [l+'\n' for l in want.split('\n')]
1430 got_lines = [l+'\n' for l in got.split('\n')]
1431 # Use difflib to find their differences.
1432 if optionflags & UNIFIED_DIFF:
1433 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1434 fromfile='Expected', tofile='Got')
1435 kind = 'unified'
1436 elif optionflags & CONTEXT_DIFF:
1437 diff = difflib.context_diff(want_lines, got_lines, n=2,
1438 fromfile='Expected', tofile='Got')
1439 kind = 'context'
1440 else:
1441 assert 0, 'Bad diff option'
1442 # Remove trailing whitespace on diff output.
1443 diff = [line.rstrip() + '\n' for line in diff]
1444 return _tag_msg("Differences (" + kind + " diff)",
1445 ''.join(diff))
1446
1447 # If we're not using diff, then simply list the expected
1448 # output followed by the actual output.
1449 return (_tag_msg("Expected", want or "Nothing") +
1450 _tag_msg("Got", got))
1451
Tim Peters19397e52004-08-06 22:02:59 +00001452class DocTestFailure(Exception):
1453 """A DocTest example has failed in debugging mode.
1454
1455 The exception instance has variables:
1456
1457 - test: the DocTest object being run
1458
1459 - excample: the Example object that failed
1460
1461 - got: the actual output
1462 """
1463 def __init__(self, test, example, got):
1464 self.test = test
1465 self.example = example
1466 self.got = got
1467
1468 def __str__(self):
1469 return str(self.test)
1470
1471class UnexpectedException(Exception):
1472 """A DocTest example has encountered an unexpected exception
1473
1474 The exception instance has variables:
1475
1476 - test: the DocTest object being run
1477
1478 - excample: the Example object that failed
1479
1480 - exc_info: the exception info
1481 """
1482 def __init__(self, test, example, exc_info):
1483 self.test = test
1484 self.example = example
1485 self.exc_info = exc_info
1486
1487 def __str__(self):
1488 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001489
Tim Peters19397e52004-08-06 22:02:59 +00001490class DebugRunner(DocTestRunner):
1491 r"""Run doc tests but raise an exception as soon as there is a failure.
1492
1493 If an unexpected exception occurs, an UnexpectedException is raised.
1494 It contains the test, the example, and the original exception:
1495
1496 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001497 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1498 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001499 >>> try:
1500 ... runner.run(test)
1501 ... except UnexpectedException, failure:
1502 ... pass
1503
1504 >>> failure.test is test
1505 True
1506
1507 >>> failure.example.want
1508 '42\n'
1509
1510 >>> exc_info = failure.exc_info
1511 >>> raise exc_info[0], exc_info[1], exc_info[2]
1512 Traceback (most recent call last):
1513 ...
1514 KeyError
1515
1516 We wrap the original exception to give the calling application
1517 access to the test and example information.
1518
1519 If the output doesn't match, then a DocTestFailure is raised:
1520
Edward Lopera1ef6112004-08-09 16:14:41 +00001521 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001522 ... >>> x = 1
1523 ... >>> x
1524 ... 2
1525 ... ''', {}, 'foo', 'foo.py', 0)
1526
1527 >>> try:
1528 ... runner.run(test)
1529 ... except DocTestFailure, failure:
1530 ... pass
1531
1532 DocTestFailure objects provide access to the test:
1533
1534 >>> failure.test is test
1535 True
1536
1537 As well as to the example:
1538
1539 >>> failure.example.want
1540 '2\n'
1541
1542 and the actual output:
1543
1544 >>> failure.got
1545 '1\n'
1546
1547 If a failure or error occurs, the globals are left intact:
1548
1549 >>> del test.globs['__builtins__']
1550 >>> test.globs
1551 {'x': 1}
1552
Edward Lopera1ef6112004-08-09 16:14:41 +00001553 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001554 ... >>> x = 2
1555 ... >>> raise KeyError
1556 ... ''', {}, 'foo', 'foo.py', 0)
1557
1558 >>> runner.run(test)
1559 Traceback (most recent call last):
1560 ...
1561 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001562
Tim Peters19397e52004-08-06 22:02:59 +00001563 >>> del test.globs['__builtins__']
1564 >>> test.globs
1565 {'x': 2}
1566
1567 But the globals are cleared if there is no error:
1568
Edward Lopera1ef6112004-08-09 16:14:41 +00001569 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001570 ... >>> x = 2
1571 ... ''', {}, 'foo', 'foo.py', 0)
1572
1573 >>> runner.run(test)
1574 (0, 1)
1575
1576 >>> test.globs
1577 {}
1578
1579 """
1580
1581 def run(self, test, compileflags=None, out=None, clear_globs=True):
1582 r = DocTestRunner.run(self, test, compileflags, out, False)
1583 if clear_globs:
1584 test.globs.clear()
1585 return r
1586
1587 def report_unexpected_exception(self, out, test, example, exc_info):
1588 raise UnexpectedException(test, example, exc_info)
1589
1590 def report_failure(self, out, test, example, got):
1591 raise DocTestFailure(test, example, got)
1592
Tim Peters8485b562004-08-04 18:46:34 +00001593######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001594## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001595######################################################################
1596# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001597
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001598def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001599 report=True, optionflags=0, extraglobs=None,
1600 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001601 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001602 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001603
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001604 Test examples in docstrings in functions and classes reachable
1605 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001606 with m.__doc__. Unless isprivate is specified, private names
1607 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001608
1609 Also test examples reachable from dict m.__test__ if it exists and is
1610 not None. m.__dict__ maps names to functions, classes and strings;
1611 function and class docstrings are tested even if the name is private;
1612 strings are tested directly, as if they were docstrings.
1613
1614 Return (#failures, #tests).
1615
1616 See doctest.__doc__ for an overview.
1617
1618 Optional keyword arg "name" gives the name of the module; by default
1619 use m.__name__.
1620
1621 Optional keyword arg "globs" gives a dict to be used as the globals
1622 when executing examples; by default, use m.__dict__. A copy of this
1623 dict is actually used for each docstring, so that each docstring's
1624 examples start with a clean slate.
1625
Tim Peters8485b562004-08-04 18:46:34 +00001626 Optional keyword arg "extraglobs" gives a dictionary that should be
1627 merged into the globals that are used to execute examples. By
1628 default, no extra globals are used. This is new in 2.4.
1629
Tim Peters8a7d2d52001-01-16 07:10:57 +00001630 Optional keyword arg "verbose" prints lots of stuff if true, prints
1631 only failures if false; by default, it's true iff "-v" is in sys.argv.
1632
Tim Peters8a7d2d52001-01-16 07:10:57 +00001633 Optional keyword arg "report" prints a summary at the end when true,
1634 else prints nothing at the end. In verbose mode, the summary is
1635 detailed, else very brief (in fact, empty if all tests passed).
1636
Tim Peters6ebe61f2003-06-27 20:48:05 +00001637 Optional keyword arg "optionflags" or's together module constants,
1638 and defaults to 0. This is new in 2.3. Possible values:
1639
1640 DONT_ACCEPT_TRUE_FOR_1
1641 By default, if an expected output block contains just "1",
1642 an actual output block containing just "True" is considered
1643 to be a match, and similarly for "0" versus "False". When
1644 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1645 is allowed.
1646
Tim Peters8485b562004-08-04 18:46:34 +00001647 DONT_ACCEPT_BLANKLINE
1648 By default, if an expected output block contains a line
1649 containing only the string "<BLANKLINE>", then that line
1650 will match a blank line in the actual output. When
1651 DONT_ACCEPT_BLANKLINE is specified, this substitution is
1652 not allowed.
1653
1654 NORMALIZE_WHITESPACE
1655 When NORMALIZE_WHITESPACE is specified, all sequences of
1656 whitespace are treated as equal. I.e., any sequence of
1657 whitespace within the expected output will match any
1658 sequence of whitespace within the actual output.
1659
1660 ELLIPSIS
1661 When ELLIPSIS is specified, then an ellipsis marker
1662 ("...") in the expected output can match any substring in
1663 the actual output.
1664
1665 UNIFIED_DIFF
1666 When UNIFIED_DIFF is specified, failures that involve
1667 multi-line expected and actual outputs will be displayed
1668 using a unified diff.
1669
1670 CONTEXT_DIFF
1671 When CONTEXT_DIFF is specified, failures that involve
1672 multi-line expected and actual outputs will be displayed
1673 using a context diff.
Tim Peters19397e52004-08-06 22:02:59 +00001674
1675 Optional keyword arg "raise_on_error" raises an exception on the
1676 first unexpected exception or failure. This allows failures to be
1677 post-mortem debugged.
1678
Tim Petersf727c6c2004-08-08 01:48:59 +00001679 Deprecated in Python 2.4:
1680 Optional keyword arg "isprivate" specifies a function used to
1681 determine whether a name is private. The default function is
1682 treat all functions as public. Optionally, "isprivate" can be
1683 set to doctest.is_private to skip over functions marked as private
1684 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001685 """
1686
1687 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001688 Advanced tomfoolery: testmod runs methods of a local instance of
1689 class doctest.Tester, then merges the results into (or creates)
1690 global Tester instance doctest.master. Methods of doctest.master
1691 can be called directly too, if you want to do something unusual.
1692 Passing report=0 to testmod is especially useful then, to delay
1693 displaying a summary. Invoke doctest.master.summarize(verbose)
1694 when you're done fiddling.
1695 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001696 if isprivate is not None:
1697 warnings.warn("the isprivate argument is deprecated; "
1698 "examine DocTestFinder.find() lists instead",
1699 DeprecationWarning)
1700
Tim Peters8485b562004-08-04 18:46:34 +00001701 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001702 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001703 # DWA - m will still be None if this wasn't invoked from the command
1704 # line, in which case the following TypeError is about as good an error
1705 # as we should expect
1706 m = sys.modules.get('__main__')
1707
Tim Peters8485b562004-08-04 18:46:34 +00001708 # Check that we were actually given a module.
1709 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001710 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001711
1712 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001713 if name is None:
1714 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001715
1716 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001717 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001718
1719 if raise_on_error:
1720 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1721 else:
1722 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1723
Tim Peters8485b562004-08-04 18:46:34 +00001724 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1725 runner.run(test)
1726
Tim Peters8a7d2d52001-01-16 07:10:57 +00001727 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001728 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001729
Tim Peters8485b562004-08-04 18:46:34 +00001730 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001731
Tim Peters8485b562004-08-04 18:46:34 +00001732def run_docstring_examples(f, globs, verbose=False, name="NoName",
1733 compileflags=None, optionflags=0):
1734 """
1735 Test examples in the given object's docstring (`f`), using `globs`
1736 as globals. Optional argument `name` is used in failure messages.
1737 If the optional argument `verbose` is true, then generate output
1738 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001739
Tim Peters8485b562004-08-04 18:46:34 +00001740 `compileflags` gives the set of flags that should be used by the
1741 Python compiler when running the examples. If not specified, then
1742 it will default to the set of future-import flags that apply to
1743 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001744
Tim Peters8485b562004-08-04 18:46:34 +00001745 Optional keyword arg `optionflags` specifies options for the
1746 testing and output. See the documentation for `testmod` for more
1747 information.
1748 """
1749 # Find, parse, and run all tests in the given module.
1750 finder = DocTestFinder(verbose=verbose, recurse=False)
1751 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1752 for test in finder.find(f, name, globs=globs):
1753 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001754
Tim Peters8485b562004-08-04 18:46:34 +00001755######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001756## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001757######################################################################
1758# This is provided only for backwards compatibility. It's not
1759# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001760
Tim Peters8485b562004-08-04 18:46:34 +00001761class Tester:
1762 def __init__(self, mod=None, globs=None, verbose=None,
1763 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001764
1765 warnings.warn("class Tester is deprecated; "
1766 "use class doctest.DocTestRunner instead",
1767 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001768 if mod is None and globs is None:
1769 raise TypeError("Tester.__init__: must specify mod or globs")
1770 if mod is not None and not _ismodule(mod):
1771 raise TypeError("Tester.__init__: mod must be a module; %r" %
1772 (mod,))
1773 if globs is None:
1774 globs = mod.__dict__
1775 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001776
Tim Peters8485b562004-08-04 18:46:34 +00001777 self.verbose = verbose
1778 self.isprivate = isprivate
1779 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001780 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001781 self.testrunner = DocTestRunner(verbose=verbose,
1782 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001783
Tim Peters8485b562004-08-04 18:46:34 +00001784 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001785 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001786 if self.verbose:
1787 print "Running string", name
1788 (f,t) = self.testrunner.run(test)
1789 if self.verbose:
1790 print f, "of", t, "examples failed in string", name
1791 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001792
Tim Petersf3f57472004-08-08 06:11:48 +00001793 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001794 f = t = 0
1795 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001796 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001797 for test in tests:
1798 (f2, t2) = self.testrunner.run(test)
1799 (f,t) = (f+f2, t+t2)
1800 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001801
Tim Peters8485b562004-08-04 18:46:34 +00001802 def rundict(self, d, name, module=None):
1803 import new
1804 m = new.module(name)
1805 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001806 if module is None:
1807 module = False
1808 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001809
Tim Peters8485b562004-08-04 18:46:34 +00001810 def run__test__(self, d, name):
1811 import new
1812 m = new.module(name)
1813 m.__test__ = d
1814 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001815
Tim Peters8485b562004-08-04 18:46:34 +00001816 def summarize(self, verbose=None):
1817 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001818
Tim Peters8485b562004-08-04 18:46:34 +00001819 def merge(self, other):
1820 d = self.testrunner._name2ft
1821 for name, (f, t) in other.testrunner._name2ft.items():
1822 if name in d:
1823 print "*** Tester.merge: '" + name + "' in both" \
1824 " testers; summing outcomes."
1825 f2, t2 = d[name]
1826 f = f + f2
1827 t = t + t2
1828 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001829
Tim Peters8485b562004-08-04 18:46:34 +00001830######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001831## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001832######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001833
Tim Peters19397e52004-08-06 22:02:59 +00001834class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001835
Edward Loper34fcb142004-08-09 02:45:41 +00001836 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
1837 checker=None):
Jim Fultona643b652004-07-14 19:06:50 +00001838 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00001839 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00001840 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00001841 self._dt_test = test
1842 self._dt_setUp = setUp
1843 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00001844
Jim Fultona643b652004-07-14 19:06:50 +00001845 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00001846 if self._dt_setUp is not None:
1847 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00001848
1849 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00001850 if self._dt_tearDown is not None:
1851 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00001852
1853 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00001854 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00001855 old = sys.stdout
1856 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00001857 runner = DocTestRunner(optionflags=self._dt_optionflags,
1858 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001859
Jim Fultona643b652004-07-14 19:06:50 +00001860 try:
Tim Peters19397e52004-08-06 22:02:59 +00001861 runner.DIVIDER = "-"*70
1862 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00001863 finally:
1864 sys.stdout = old
1865
1866 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00001867 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00001868
Tim Peters19397e52004-08-06 22:02:59 +00001869 def format_failure(self, err):
1870 test = self._dt_test
1871 if test.lineno is None:
1872 lineno = 'unknown line number'
1873 else:
1874 lineno = 'line %s' % test.lineno
1875 lname = '.'.join(test.name.split('.')[-1:])
1876 return ('Failed doctest test for %s\n'
1877 ' File "%s", line %s, in %s\n\n%s'
1878 % (test.name, test.filename, lineno, lname, err)
1879 )
1880
1881 def debug(self):
1882 r"""Run the test case without results and without catching exceptions
1883
1884 The unit test framework includes a debug method on test cases
1885 and test suites to support post-mortem debugging. The test code
1886 is run in such a way that errors are not caught. This way a
1887 caller can catch the errors and initiate post-mortem debugging.
1888
1889 The DocTestCase provides a debug method that raises
1890 UnexpectedException errors if there is an unexepcted
1891 exception:
1892
Edward Lopera1ef6112004-08-09 16:14:41 +00001893 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00001894 ... {}, 'foo', 'foo.py', 0)
1895 >>> case = DocTestCase(test)
1896 >>> try:
1897 ... case.debug()
1898 ... except UnexpectedException, failure:
1899 ... pass
1900
1901 The UnexpectedException contains the test, the example, and
1902 the original exception:
1903
1904 >>> failure.test is test
1905 True
1906
1907 >>> failure.example.want
1908 '42\n'
1909
1910 >>> exc_info = failure.exc_info
1911 >>> raise exc_info[0], exc_info[1], exc_info[2]
1912 Traceback (most recent call last):
1913 ...
1914 KeyError
1915
1916 If the output doesn't match, then a DocTestFailure is raised:
1917
Edward Lopera1ef6112004-08-09 16:14:41 +00001918 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001919 ... >>> x = 1
1920 ... >>> x
1921 ... 2
1922 ... ''', {}, 'foo', 'foo.py', 0)
1923 >>> case = DocTestCase(test)
1924
1925 >>> try:
1926 ... case.debug()
1927 ... except DocTestFailure, failure:
1928 ... pass
1929
1930 DocTestFailure objects provide access to the test:
1931
1932 >>> failure.test is test
1933 True
1934
1935 As well as to the example:
1936
1937 >>> failure.example.want
1938 '2\n'
1939
1940 and the actual output:
1941
1942 >>> failure.got
1943 '1\n'
1944
1945 """
1946
Edward Loper34fcb142004-08-09 02:45:41 +00001947 runner = DebugRunner(optionflags=self._dt_optionflags,
1948 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001949 runner.run(self._dt_test, out=nooutput)
Jim Fultona643b652004-07-14 19:06:50 +00001950
1951 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00001952 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00001953
1954 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00001955 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00001956 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
1957
1958 __str__ = __repr__
1959
1960 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00001961 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00001962
Tim Peters19397e52004-08-06 22:02:59 +00001963def nooutput(*args):
1964 pass
Jim Fultona643b652004-07-14 19:06:50 +00001965
Tim Peters19397e52004-08-06 22:02:59 +00001966def DocTestSuite(module=None, globs=None, extraglobs=None,
1967 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00001968 setUp=lambda: None, tearDown=lambda: None,
1969 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00001970 """
Tim Peters19397e52004-08-06 22:02:59 +00001971 Convert doctest tests for a mudule to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00001972
Tim Peters19397e52004-08-06 22:02:59 +00001973 This converts each documentation string in a module that
1974 contains doctest tests to a unittest test case. If any of the
1975 tests in a doc string fail, then the test case fails. An exception
1976 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00001977 (sometimes approximate) line number.
1978
Tim Peters19397e52004-08-06 22:02:59 +00001979 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00001980 can be either a module or a module name.
1981
1982 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00001983 """
Jim Fultona643b652004-07-14 19:06:50 +00001984
Tim Peters8485b562004-08-04 18:46:34 +00001985 if test_finder is None:
1986 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00001987
Tim Peters19397e52004-08-06 22:02:59 +00001988 module = _normalize_module(module)
1989 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
1990 if globs is None:
1991 globs = module.__dict__
1992 if not tests: # [XX] why do we want to do this?
1993 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00001994
1995 tests.sort()
1996 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00001997 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00001998 if len(test.examples) == 0:
1999 continue
Tim Peters8485b562004-08-04 18:46:34 +00002000 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002001 filename = module.__file__
2002 if filename.endswith(".pyc"):
2003 filename = filename[:-1]
2004 elif filename.endswith(".pyo"):
2005 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002006 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002007 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2008 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002009
2010 return suite
2011
2012class DocFileCase(DocTestCase):
2013
2014 def id(self):
2015 return '_'.join(self._dt_test.name.split('.'))
2016
2017 def __repr__(self):
2018 return self._dt_test.filename
2019 __str__ = __repr__
2020
2021 def format_failure(self, err):
2022 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2023 % (self._dt_test.name, self._dt_test.filename, err)
2024 )
2025
2026def DocFileTest(path, package=None, globs=None,
2027 setUp=None, tearDown=None,
2028 optionflags=0):
2029 package = _normalize_module(package)
2030 name = path.split('/')[-1]
2031 dir = os.path.split(package.__file__)[0]
2032 path = os.path.join(dir, *(path.split('/')))
2033 doc = open(path).read()
2034
2035 if globs is None:
2036 globs = {}
2037
Edward Lopera1ef6112004-08-09 16:14:41 +00002038 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002039
2040 return DocFileCase(test, optionflags, setUp, tearDown)
2041
2042def DocFileSuite(*paths, **kw):
2043 """Creates a suite of doctest files.
2044
2045 One or more text file paths are given as strings. These should
2046 use "/" characters to separate path segments. Paths are relative
2047 to the directory of the calling module, or relative to the package
2048 passed as a keyword argument.
2049
2050 A number of options may be provided as keyword arguments:
2051
2052 package
2053 The name of a Python package. Text-file paths will be
2054 interpreted relative to the directory containing this package.
2055 The package may be supplied as a package object or as a dotted
2056 package name.
2057
2058 setUp
2059 The name of a set-up function. This is called before running the
2060 tests in each file.
2061
2062 tearDown
2063 The name of a tear-down function. This is called after running the
2064 tests in each file.
2065
2066 globs
2067 A dictionary containing initial global variables for the tests.
2068 """
2069 suite = unittest.TestSuite()
2070
2071 # We do this here so that _normalize_module is called at the right
2072 # level. If it were called in DocFileTest, then this function
2073 # would be the caller and we might guess the package incorrectly.
2074 kw['package'] = _normalize_module(kw.get('package'))
2075
2076 for path in paths:
2077 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002078
Tim Petersdb3756d2003-06-29 05:30:48 +00002079 return suite
2080
Tim Peters8485b562004-08-04 18:46:34 +00002081######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002082## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002083######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002084
Tim Peters19397e52004-08-06 22:02:59 +00002085def script_from_examples(s):
2086 r"""Extract script from text with examples.
2087
2088 Converts text with examples to a Python script. Example input is
2089 converted to regular code. Example output and all other words
2090 are converted to comments:
2091
2092 >>> text = '''
2093 ... Here are examples of simple math.
2094 ...
2095 ... Python has super accurate integer addition
2096 ...
2097 ... >>> 2 + 2
2098 ... 5
2099 ...
2100 ... And very friendly error messages:
2101 ...
2102 ... >>> 1/0
2103 ... To Infinity
2104 ... And
2105 ... Beyond
2106 ...
2107 ... You can use logic if you want:
2108 ...
2109 ... >>> if 0:
2110 ... ... blah
2111 ... ... blah
2112 ... ...
2113 ...
2114 ... Ho hum
2115 ... '''
2116
2117 >>> print script_from_examples(text)
2118 # Here are examples of simple math.
2119 #
2120 # Python has super accurate integer addition
2121 #
2122 2 + 2
2123 # Expected:
2124 # 5
2125 #
2126 # And very friendly error messages:
2127 #
2128 1/0
2129 # Expected:
2130 # To Infinity
2131 # And
2132 # Beyond
2133 #
2134 # You can use logic if you want:
2135 #
2136 if 0:
2137 blah
2138 blah
2139 <BLANKLINE>
2140 #
2141 # Ho hum
2142 """
2143
Edward Lopera1ef6112004-08-09 16:14:41 +00002144 return DocTestParser().get_program(s)
Tim Peters19397e52004-08-06 22:02:59 +00002145
Tim Peters8485b562004-08-04 18:46:34 +00002146def _want_comment(example):
2147 """
Tim Peters19397e52004-08-06 22:02:59 +00002148 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002149 """
Jim Fultona643b652004-07-14 19:06:50 +00002150 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002151 want = example.want
2152 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002153 if want[-1] == '\n':
2154 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002155 want = "\n# ".join(want.split("\n"))
2156 want = "\n# Expected:\n# %s" % want
2157 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002158
2159def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002160 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002161
2162 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002163 test to be debugged and the name (within the module) of the object
2164 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002165 """
Tim Peters8485b562004-08-04 18:46:34 +00002166 module = _normalize_module(module)
2167 tests = DocTestFinder().find(module)
2168 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002169 if not test:
2170 raise ValueError(name, "not found in tests")
2171 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002172 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002173 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002174
Jim Fultona643b652004-07-14 19:06:50 +00002175def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002176 """Debug a single doctest docstring, in argument `src`'"""
2177 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002178 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002179
Jim Fultona643b652004-07-14 19:06:50 +00002180def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002181 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002182 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002183
Tim Petersdb3756d2003-06-29 05:30:48 +00002184 srcfilename = tempfile.mktemp("doctestdebug.py")
Tim Peters8485b562004-08-04 18:46:34 +00002185 f = open(srcfilename, 'w')
2186 f.write(src)
2187 f.close()
2188
Jim Fultona643b652004-07-14 19:06:50 +00002189 if globs:
2190 globs = globs.copy()
2191 else:
2192 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002193
Tim Peters8485b562004-08-04 18:46:34 +00002194 if pm:
2195 try:
2196 execfile(srcfilename, globs, globs)
2197 except:
2198 print sys.exc_info()[1]
2199 pdb.post_mortem(sys.exc_info()[2])
2200 else:
2201 # Note that %r is vital here. '%s' instead can, e.g., cause
2202 # backslashes to get treated as metacharacters on Windows.
2203 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002204
Jim Fultona643b652004-07-14 19:06:50 +00002205def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002206 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002207
2208 Provide the module (or dotted name of the module) containing the
2209 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002210 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002211 """
Tim Peters8485b562004-08-04 18:46:34 +00002212 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002213 testsrc = testsource(module, name)
2214 debug_script(testsrc, pm, module.__dict__)
2215
Tim Peters8485b562004-08-04 18:46:34 +00002216######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002217## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002218######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002219class _TestClass:
2220 """
2221 A pointless class, for sanity-checking of docstring testing.
2222
2223 Methods:
2224 square()
2225 get()
2226
2227 >>> _TestClass(13).get() + _TestClass(-12).get()
2228 1
2229 >>> hex(_TestClass(13).square().get())
2230 '0xa9'
2231 """
2232
2233 def __init__(self, val):
2234 """val -> _TestClass object with associated value val.
2235
2236 >>> t = _TestClass(123)
2237 >>> print t.get()
2238 123
2239 """
2240
2241 self.val = val
2242
2243 def square(self):
2244 """square() -> square TestClass's associated value
2245
2246 >>> _TestClass(13).square().get()
2247 169
2248 """
2249
2250 self.val = self.val ** 2
2251 return self
2252
2253 def get(self):
2254 """get() -> return TestClass's associated value.
2255
2256 >>> x = _TestClass(-42)
2257 >>> print x.get()
2258 -42
2259 """
2260
2261 return self.val
2262
2263__test__ = {"_TestClass": _TestClass,
2264 "string": r"""
2265 Example of a string object, searched as-is.
2266 >>> x = 1; y = 2
2267 >>> x + y, x * y
2268 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002269 """,
2270 "bool-int equivalence": r"""
2271 In 2.2, boolean expressions displayed
2272 0 or 1. By default, we still accept
2273 them. This can be disabled by passing
2274 DONT_ACCEPT_TRUE_FOR_1 to the new
2275 optionflags argument.
2276 >>> 4 == 4
2277 1
2278 >>> 4 == 4
2279 True
2280 >>> 4 > 4
2281 0
2282 >>> 4 > 4
2283 False
2284 """,
Tim Peters8485b562004-08-04 18:46:34 +00002285 "blank lines": r"""
2286 Blank lines can be marked with <BLANKLINE>:
2287 >>> print 'foo\n\nbar\n'
2288 foo
2289 <BLANKLINE>
2290 bar
2291 <BLANKLINE>
2292 """,
2293 }
2294# "ellipsis": r"""
2295# If the ellipsis flag is used, then '...' can be used to
2296# elide substrings in the desired output:
2297# >>> print range(1000)
2298# [0, 1, 2, ..., 999]
2299# """,
2300# "whitespace normalization": r"""
2301# If the whitespace normalization flag is used, then
2302# differences in whitespace are ignored.
2303# >>> print range(30)
2304# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2305# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2306# 27, 28, 29]
2307# """,
2308# }
2309
2310def test1(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002311>>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2312... "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002313>>> from doctest import Tester
2314>>> t = Tester(globs={'x': 42}, verbose=0)
2315>>> t.runstring(r'''
2316... >>> x = x * 2
2317... >>> print x
2318... 42
2319... ''', 'XYZ')
2320**********************************************************************
2321Failure in example: print x
2322from line #2 of XYZ
2323Expected: 42
2324Got: 84
2325(1, 2)
2326>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2327(0, 2)
2328>>> t.summarize()
2329**********************************************************************
23301 items had failures:
2331 1 of 2 in XYZ
2332***Test Failed*** 1 failures.
2333(1, 4)
2334>>> t.summarize(verbose=1)
23351 items passed all tests:
2336 2 tests in example2
2337**********************************************************************
23381 items had failures:
2339 1 of 2 in XYZ
23404 tests in 2 items.
23413 passed and 1 failed.
2342***Test Failed*** 1 failures.
2343(1, 4)
2344"""
2345
2346def test2(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002347 >>> warnings.filterwarnings("ignore", "class Tester",
2348 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002349 >>> t = Tester(globs={}, verbose=1)
2350 >>> test = r'''
2351 ... # just an example
2352 ... >>> x = 1 + 2
2353 ... >>> x
2354 ... 3
2355 ... '''
2356 >>> t.runstring(test, "Example")
2357 Running string Example
2358 Trying: x = 1 + 2
2359 Expecting: nothing
2360 ok
2361 Trying: x
2362 Expecting: 3
2363 ok
2364 0 of 2 examples failed in string Example
2365 (0, 2)
2366"""
2367def test3(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002368 >>> warnings.filterwarnings("ignore", "class Tester",
2369 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002370 >>> t = Tester(globs={}, verbose=0)
2371 >>> def _f():
2372 ... '''Trivial docstring example.
2373 ... >>> assert 2 == 2
2374 ... '''
2375 ... return 32
2376 ...
2377 >>> t.rundoc(_f) # expect 0 failures in 1 example
2378 (0, 1)
2379"""
2380def test4(): """
2381 >>> import new
2382 >>> m1 = new.module('_m1')
2383 >>> m2 = new.module('_m2')
2384 >>> test_data = \"""
2385 ... def _f():
2386 ... '''>>> assert 1 == 1
2387 ... '''
2388 ... def g():
2389 ... '''>>> assert 2 != 1
2390 ... '''
2391 ... class H:
2392 ... '''>>> assert 2 > 1
2393 ... '''
2394 ... def bar(self):
2395 ... '''>>> assert 1 < 2
2396 ... '''
2397 ... \"""
2398 >>> exec test_data in m1.__dict__
2399 >>> exec test_data in m2.__dict__
2400 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2401
2402 Tests that objects outside m1 are excluded:
2403
Tim Peters3ddd60a2004-08-08 02:43:33 +00002404 >>> warnings.filterwarnings("ignore", "class Tester",
2405 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002406 >>> t = Tester(globs={}, verbose=0)
Tim Petersf727c6c2004-08-08 01:48:59 +00002407 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Tim Peters8485b562004-08-04 18:46:34 +00002408 (0, 4)
2409
Tim Petersf727c6c2004-08-08 01:48:59 +00002410 Once more, not excluding stuff outside m1:
Tim Peters8485b562004-08-04 18:46:34 +00002411
2412 >>> t = Tester(globs={}, verbose=0)
2413 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2414 (0, 8)
2415
2416 The exclusion of objects from outside the designated module is
2417 meant to be invoked automagically by testmod.
2418
Tim Petersf727c6c2004-08-08 01:48:59 +00002419 >>> testmod(m1, verbose=False)
2420 (0, 4)
Tim Peters8485b562004-08-04 18:46:34 +00002421"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002422
2423def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002424 #import doctest
2425 #doctest.testmod(doctest, verbose=False,
2426 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2427 # UNIFIED_DIFF)
2428 #print '~'*70
2429 r = unittest.TextTestRunner()
2430 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002431
2432if __name__ == "__main__":
2433 _test()