blob: a34b0a1928ab05e774682e375437cebfb0fdec7b [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8485b562004-08-04 18:46:34 +00002# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
Tim Peters19397e52004-08-06 22:02:59 +00003# Major enhancements and refactoring by:
Tim Peters8485b562004-08-04 18:46:34 +00004# Jim Fulton
5# Edward Loper
Tim Peters8a7d2d52001-01-16 07:10:57 +00006
7# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
8
Martin v. Löwis92816de2004-05-31 19:01:00 +00009r"""Module doctest -- a framework for running examples in docstrings.
Tim Peters8a7d2d52001-01-16 07:10:57 +000010
11NORMAL USAGE
12
Tim Peters80e53142004-08-09 04:34:45 +000013In simplest use, end each module M to be tested with:
Tim Peters8a7d2d52001-01-16 07:10:57 +000014
15def _test():
Tim Peters80e53142004-08-09 04:34:45 +000016 import doctest
17 return doctest.testmod()
Tim Peters8a7d2d52001-01-16 07:10:57 +000018
19if __name__ == "__main__":
20 _test()
21
22Then running the module as a script will cause the examples in the
23docstrings to get executed and verified:
24
25python M.py
26
27This won't display anything unless an example fails, in which case the
28failing example(s) and the cause(s) of the failure(s) are printed to stdout
29(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
30line of output is "Test failed.".
31
32Run it with the -v switch instead:
33
34python M.py -v
35
36and a detailed report of all examples tried is printed to stdout, along
37with assorted summaries at the end.
38
Tim Peters80e53142004-08-09 04:34:45 +000039You can force verbose mode by passing "verbose=True" to testmod, or prohibit
40it by passing "verbose=False". In either of those cases, sys.argv is not
Tim Peters8a7d2d52001-01-16 07:10:57 +000041examined by testmod.
42
43In any case, testmod returns a 2-tuple of ints (f, t), where f is the
44number of docstring examples that failed and t is the total number of
45docstring examples attempted.
46
Tim Peters80e53142004-08-09 04:34:45 +000047There are a variety of other ways to run doctests, including integration
48with the unittest framework, and support for running non-Python text
49files containing doctests. There are also many ways to override parts
50of doctest's default behaviors. See the Library Reference Manual for
51details.
52
Tim Peters8a7d2d52001-01-16 07:10:57 +000053
54WHICH DOCSTRINGS ARE EXAMINED?
55
56+ M.__doc__.
57
58+ f.__doc__ for all functions f in M.__dict__.values(), except those
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000059 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000060
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000061+ C.__doc__ for all classes C in M.__dict__.values(), except those
62 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000063
64+ If M.__test__ exists and "is true", it must be a dict, and
65 each entry maps a (string) name to a function object, class object, or
66 string. Function and class object docstrings found from M.__test__
Tim Peters80e53142004-08-09 04:34:45 +000067 are searched, and strings are searched directly as if they were docstrings.
68 In output, a key K in M.__test__ appears with name
Tim Peters8a7d2d52001-01-16 07:10:57 +000069 <name of M>.__test__.K
70
71Any classes found are recursively searched similarly, to test docstrings in
Tim Peters80e53142004-08-09 04:34:45 +000072their contained methods and nested classes.
Tim Peters8a7d2d52001-01-16 07:10:57 +000073
Tim Peters8a7d2d52001-01-16 07:10:57 +000074
Tim Peters8a7d2d52001-01-16 07:10:57 +000075WHAT'S THE EXECUTION CONTEXT?
76
77By default, each time testmod finds a docstring to test, it uses a *copy*
78of M's globals (so that running tests on a module doesn't change the
79module's real globals, and so that one test in M can't leave behind crumbs
80that accidentally allow another test to work). This means examples can
81freely use any names defined at top-level in M. It also means that sloppy
82imports (see above) can cause examples in external docstrings to use
83globals inappropriate for them.
84
85You can force use of your own dict as the execution context by passing
86"globs=your_dict" to testmod instead. Presumably this would be a copy of
87M.__dict__ merged with the globals from other imported modules.
88
89
Tim Peters8a7d2d52001-01-16 07:10:57 +000090WHAT ABOUT EXCEPTIONS?
91
92No problem, as long as the only output generated by the example is the
93traceback itself. For example:
94
Tim Peters60e23f42001-02-14 00:43:21 +000095 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +000096 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +000097 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +000098 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +000099 >>>
100
Tim Peters80e53142004-08-09 04:34:45 +0000101Note that only the exception type and value are compared.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000102
103
Tim Peters80e53142004-08-09 04:34:45 +0000104SO WHAT DOES A DOCTEST EXAMPLE LOOK LIKE ALREADY!?
Tim Peters8a7d2d52001-01-16 07:10:57 +0000105
106Oh ya. It's easy! In most cases a copy-and-paste of an interactive
107console session works fine -- just make sure the leading whitespace is
108rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
109right, but doctest is not in the business of guessing what you think a tab
110means).
111
112 >>> # comments are ignored
113 >>> x = 12
114 >>> x
115 12
116 >>> if x == 13:
117 ... print "yes"
118 ... else:
119 ... print "no"
120 ... print "NO"
121 ... print "NO!!!"
122 ...
123 no
124 NO
125 NO!!!
126 >>>
127
128Any expected output must immediately follow the final ">>>" or "..." line
129containing the code, and the expected output (if any) extends to the next
130">>>" or all-whitespace line. That's it.
131
132Bummers:
133
Tim Peters8a7d2d52001-01-16 07:10:57 +0000134+ Output to stdout is captured, but not output to stderr (exception
135 tracebacks are captured via a different means).
136
Martin v. Löwis92816de2004-05-31 19:01:00 +0000137+ If you continue a line via backslashing in an interactive session,
138 or for any other reason use a backslash, you should use a raw
139 docstring, which will preserve your backslahses exactly as you type
140 them:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000141
Tim Peters4e0e1b62004-07-07 20:54:48 +0000142 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000143 ... r'''Backslashes in a raw docstring: m\n'''
144 >>> print f.__doc__
145 Backslashes in a raw docstring: m\n
Tim Peters8a7d2d52001-01-16 07:10:57 +0000146
Martin v. Löwis92816de2004-05-31 19:01:00 +0000147 Otherwise, the backslash will be interpreted as part of the string.
148 E.g., the "\n" above would be interpreted as a newline character.
149 Alternatively, you can double each backslash in the doctest version
150 (and not use a raw string):
151
Tim Peters4e0e1b62004-07-07 20:54:48 +0000152 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000153 ... '''Backslashes in a raw docstring: m\\n'''
154 >>> print f.__doc__
155 Backslashes in a raw docstring: m\n
Tim Peters4e0e1b62004-07-07 20:54:48 +0000156
Tim Peters8a7d2d52001-01-16 07:10:57 +0000157The starting column doesn't matter:
158
159>>> assert "Easy!"
160 >>> import math
161 >>> math.floor(1.9)
162 1.0
163
164and as many leading whitespace characters are stripped from the expected
165output as appeared in the initial ">>>" line that triggered it.
166
167If you execute this very file, the examples above will be found and
Tim Peters80e53142004-08-09 04:34:45 +0000168executed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000169"""
Edward Loper8e4a34b2004-08-12 02:34:27 +0000170__docformat__ = 'reStructuredText en'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000171
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000172__all__ = [
Edward Loperb7503ff2004-08-19 19:19:03 +0000173 # 0, Option Flags
174 'register_optionflag',
175 'DONT_ACCEPT_TRUE_FOR_1',
176 'DONT_ACCEPT_BLANKLINE',
177 'NORMALIZE_WHITESPACE',
178 'ELLIPSIS',
Tim Peters1fbf9c52004-09-04 17:21:02 +0000179 'IGNORE_EXCEPTION_DETAIL',
Tim Petersba601962004-09-04 15:04:06 +0000180 'COMPARISON_FLAGS',
Edward Loper71f55af2004-08-26 01:41:51 +0000181 'REPORT_UDIFF',
182 'REPORT_CDIFF',
183 'REPORT_NDIFF',
Jim Fultonf54bad42004-08-28 14:57:56 +0000184 'REPORT_ONLY_FIRST_FAILURE',
Tim Petersba601962004-09-04 15:04:06 +0000185 'REPORTING_FLAGS',
Edward Loperb7503ff2004-08-19 19:19:03 +0000186 # 1. Utility Functions
Tim Peters8485b562004-08-04 18:46:34 +0000187 'is_private',
Edward Loperb7503ff2004-08-19 19:19:03 +0000188 # 2. Example & DocTest
Tim Peters8485b562004-08-04 18:46:34 +0000189 'Example',
190 'DocTest',
Edward Loperb7503ff2004-08-19 19:19:03 +0000191 # 3. Doctest Parser
192 'DocTestParser',
193 # 4. Doctest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000194 'DocTestFinder',
Edward Loperb7503ff2004-08-19 19:19:03 +0000195 # 5. Doctest Runner
Tim Peters8485b562004-08-04 18:46:34 +0000196 'DocTestRunner',
Edward Loperb7503ff2004-08-19 19:19:03 +0000197 'OutputChecker',
198 'DocTestFailure',
199 'UnexpectedException',
200 'DebugRunner',
201 # 6. Test Functions
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000202 'testmod',
Edward Loper052d0cd2004-09-19 17:19:33 +0000203 'testfile',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000204 'run_docstring_examples',
Edward Loperb7503ff2004-08-19 19:19:03 +0000205 # 7. Tester
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000206 'Tester',
Edward Loperb7503ff2004-08-19 19:19:03 +0000207 # 8. Unittest Support
Tim Peters19397e52004-08-06 22:02:59 +0000208 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000209 'DocTestSuite',
Edward Loperb7503ff2004-08-19 19:19:03 +0000210 'DocFileCase',
211 'DocFileTest',
212 'DocFileSuite',
213 # 9. Debugging Support
214 'script_from_examples',
Tim Petersdb3756d2003-06-29 05:30:48 +0000215 'testsource',
Edward Loperb7503ff2004-08-19 19:19:03 +0000216 'debug_src',
217 'debug_script',
Tim Petersdb3756d2003-06-29 05:30:48 +0000218 'debug',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000219]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000220
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000221import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000222
Tim Peters19397e52004-08-06 22:02:59 +0000223import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000224import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000225import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000226from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000227
Tim Petersdd50cb72004-08-23 22:42:55 +0000228# Don't whine about the deprecated is_private function in this
229# module's tests.
230warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
231 __name__, 0)
232
Jim Fulton356fd192004-08-09 11:34:47 +0000233real_pdb_set_trace = pdb.set_trace
234
Tim Peters19397e52004-08-06 22:02:59 +0000235# There are 4 basic classes:
236# - Example: a <source, want> pair, plus an intra-docstring line number.
237# - DocTest: a collection of examples, parsed from a docstring, plus
238# info about where the docstring came from (name, filename, lineno).
239# - DocTestFinder: extracts DocTests from a given object's docstring and
240# its contained objects' docstrings.
241# - DocTestRunner: runs DocTest cases, and accumulates statistics.
242#
243# So the basic picture is:
244#
245# list of:
246# +------+ +---------+ +-------+
247# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
248# +------+ +---------+ +-------+
249# | Example |
250# | ... |
251# | Example |
252# +---------+
253
Edward Loperac20f572004-08-12 02:02:24 +0000254# Option constants.
Tim Peters38330fe2004-08-30 16:19:24 +0000255
Edward Loperac20f572004-08-12 02:02:24 +0000256OPTIONFLAGS_BY_NAME = {}
257def register_optionflag(name):
258 flag = 1 << len(OPTIONFLAGS_BY_NAME)
259 OPTIONFLAGS_BY_NAME[name] = flag
260 return flag
261
262DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
263DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
264NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
265ELLIPSIS = register_optionflag('ELLIPSIS')
Tim Peters1fbf9c52004-09-04 17:21:02 +0000266IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
Tim Peters38330fe2004-08-30 16:19:24 +0000267
268COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
269 DONT_ACCEPT_BLANKLINE |
270 NORMALIZE_WHITESPACE |
Tim Peters1fbf9c52004-09-04 17:21:02 +0000271 ELLIPSIS |
272 IGNORE_EXCEPTION_DETAIL)
Tim Peters38330fe2004-08-30 16:19:24 +0000273
Edward Loper71f55af2004-08-26 01:41:51 +0000274REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
275REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
276REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
Edward Lopera89f88d2004-08-26 02:45:51 +0000277REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
Edward Loperac20f572004-08-12 02:02:24 +0000278
Tim Peters38330fe2004-08-30 16:19:24 +0000279REPORTING_FLAGS = (REPORT_UDIFF |
280 REPORT_CDIFF |
281 REPORT_NDIFF |
282 REPORT_ONLY_FIRST_FAILURE)
283
Edward Loperac20f572004-08-12 02:02:24 +0000284# Special string markers for use in `want` strings:
285BLANKLINE_MARKER = '<BLANKLINE>'
286ELLIPSIS_MARKER = '...'
287
Tim Peters8485b562004-08-04 18:46:34 +0000288######################################################################
289## Table of Contents
290######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000291# 1. Utility Functions
292# 2. Example & DocTest -- store test cases
293# 3. DocTest Parser -- extracts examples from strings
294# 4. DocTest Finder -- extracts test cases from objects
295# 5. DocTest Runner -- runs test cases
296# 6. Test Functions -- convenient wrappers for testing
297# 7. Tester Class -- for backwards compatibility
298# 8. Unittest Support
299# 9. Debugging Support
300# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000301
Tim Peters8485b562004-08-04 18:46:34 +0000302######################################################################
303## 1. Utility Functions
304######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000305
306def is_private(prefix, base):
307 """prefix, base -> true iff name prefix + "." + base is "private".
308
309 Prefix may be an empty string, and base does not contain a period.
310 Prefix is ignored (although functions you write conforming to this
311 protocol may make use of it).
312 Return true iff base begins with an (at least one) underscore, but
313 does not both begin and end with (at least) two underscores.
314
315 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000316 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000317 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000318 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000319 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000320 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000321 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000322 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000323 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000324 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000325 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000326 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000327 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000328 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000329 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000330 warnings.warn("is_private is deprecated; it wasn't useful; "
331 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000332 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000333 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
334
Tim Peters8485b562004-08-04 18:46:34 +0000335def _extract_future_flags(globs):
336 """
337 Return the compiler-flags associated with the future features that
338 have been imported into the given namespace (globs).
339 """
340 flags = 0
341 for fname in __future__.all_feature_names:
342 feature = globs.get(fname, None)
343 if feature is getattr(__future__, fname):
344 flags |= feature.compiler_flag
345 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000346
Tim Peters8485b562004-08-04 18:46:34 +0000347def _normalize_module(module, depth=2):
348 """
349 Return the module specified by `module`. In particular:
350 - If `module` is a module, then return module.
351 - If `module` is a string, then import and return the
352 module with that name.
353 - If `module` is None, then return the calling module.
354 The calling module is assumed to be the module of
355 the stack frame at the given depth in the call stack.
356 """
357 if inspect.ismodule(module):
358 return module
359 elif isinstance(module, (str, unicode)):
360 return __import__(module, globals(), locals(), ["*"])
361 elif module is None:
362 return sys.modules[sys._getframe(depth).f_globals['__name__']]
363 else:
364 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000365
Edward Loperaacf0832004-08-26 01:19:50 +0000366def _indent(s, indent=4):
Tim Peters8485b562004-08-04 18:46:34 +0000367 """
Edward Loperaacf0832004-08-26 01:19:50 +0000368 Add the given number of space characters to the beginning every
369 non-blank line in `s`, and return the result.
Tim Peters8485b562004-08-04 18:46:34 +0000370 """
Edward Loperaacf0832004-08-26 01:19:50 +0000371 # This regexp matches the start of non-blank lines:
372 return re.sub('(?m)^(?!$)', indent*' ', s)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000373
Edward Loper8e4a34b2004-08-12 02:34:27 +0000374def _exception_traceback(exc_info):
375 """
376 Return a string containing a traceback message for the given
377 exc_info tuple (as returned by sys.exc_info()).
378 """
379 # Get a traceback message.
380 excout = StringIO()
381 exc_type, exc_val, exc_tb = exc_info
382 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
383 return excout.getvalue()
384
Tim Peters8485b562004-08-04 18:46:34 +0000385# Override some StringIO methods.
386class _SpoofOut(StringIO):
387 def getvalue(self):
388 result = StringIO.getvalue(self)
389 # If anything at all was written, make sure there's a trailing
390 # newline. There's no way for the expected output to indicate
391 # that a trailing newline is missing.
392 if result and not result.endswith("\n"):
393 result += "\n"
394 # Prevent softspace from screwing up the next test case, in
395 # case they used print with a trailing comma in an example.
396 if hasattr(self, "softspace"):
397 del self.softspace
398 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000399
Tim Peters8485b562004-08-04 18:46:34 +0000400 def truncate(self, size=None):
401 StringIO.truncate(self, size)
402 if hasattr(self, "softspace"):
403 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000404
Tim Peters26b3ebb2004-08-19 08:10:08 +0000405# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000406def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000407 """
408 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000409 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000410 False
411 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000412 if ELLIPSIS_MARKER not in want:
413 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000414
Tim Peters26b3ebb2004-08-19 08:10:08 +0000415 # Find "the real" strings.
416 ws = want.split(ELLIPSIS_MARKER)
417 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000418
Tim Petersdc5de3b2004-08-19 14:06:20 +0000419 # Deal with exact matches possibly needed at one or both ends.
420 startpos, endpos = 0, len(got)
421 w = ws[0]
422 if w: # starts with exact match
423 if got.startswith(w):
424 startpos = len(w)
425 del ws[0]
426 else:
427 return False
428 w = ws[-1]
429 if w: # ends with exact match
430 if got.endswith(w):
431 endpos -= len(w)
432 del ws[-1]
433 else:
434 return False
435
436 if startpos > endpos:
437 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000438 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000439 return False
440
441 # For the rest, we only need to find the leftmost non-overlapping
442 # match for each piece. If there's no overall match that way alone,
443 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000444 for w in ws:
445 # w may be '' at times, if there are consecutive ellipses, or
446 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000447 # Search for an empty string succeeds, and doesn't change startpos.
448 startpos = got.find(w, startpos, endpos)
449 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000450 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000451 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000452
Tim Petersdc5de3b2004-08-19 14:06:20 +0000453 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000454
Edward Loper00f8da72004-08-26 18:05:07 +0000455def _comment_line(line):
456 "Return a commented form of the given line"
457 line = line.rstrip()
458 if line:
459 return '# '+line
460 else:
461 return '#'
462
Edward Loper2de91ba2004-08-27 02:07:46 +0000463class _OutputRedirectingPdb(pdb.Pdb):
464 """
465 A specialized version of the python debugger that redirects stdout
466 to a given stream when interacting with the user. Stdout is *not*
467 redirected when traced code is executed.
468 """
469 def __init__(self, out):
470 self.__out = out
471 pdb.Pdb.__init__(self)
472
473 def trace_dispatch(self, *args):
474 # Redirect stdout to the given stream.
475 save_stdout = sys.stdout
476 sys.stdout = self.__out
477 # Call Pdb's trace dispatch method.
478 pdb.Pdb.trace_dispatch(self, *args)
479 # Restore stdout.
480 sys.stdout = save_stdout
481
Edward Loper052d0cd2004-09-19 17:19:33 +0000482def _module_relative_path(module, path):
483 if not inspect.ismodule(module):
484 raise TypeError, 'Expected a module: %r' % module
485 if path.startswith('/'):
486 raise ValueError, 'Module-relative files may not have absolute paths'
487
488 # Find the base directory for the path.
489 if hasattr(module, '__file__'):
490 # A normal module/package
491 basedir = os.path.split(module.__file__)[0]
492 elif module.__name__ == '__main__':
493 # An interactive session.
494 if len(sys.argv)>0 and sys.argv[0] != '':
495 basedir = os.path.split(sys.argv[0])[0]
496 else:
497 basedir = os.curdir
498 else:
499 # A module w/o __file__ (this includes builtins)
500 raise ValueError("Can't resolve paths relative to the module " +
501 module + " (it has no __file__)")
502
503 # Combine the base directory and the path.
504 return os.path.join(basedir, *(path.split('/')))
505
Tim Peters8485b562004-08-04 18:46:34 +0000506######################################################################
507## 2. Example & DocTest
508######################################################################
509## - An "example" is a <source, want> pair, where "source" is a
510## fragment of source code, and "want" is the expected output for
511## "source." The Example class also includes information about
512## where the example was extracted from.
513##
Edward Lopera1ef6112004-08-09 16:14:41 +0000514## - A "doctest" is a collection of examples, typically extracted from
515## a string (such as an object's docstring). The DocTest class also
516## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000517
Tim Peters8485b562004-08-04 18:46:34 +0000518class Example:
519 """
520 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000521 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000522
Edward Loper74bca7a2004-08-12 02:27:44 +0000523 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000524 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000525
Edward Loper74bca7a2004-08-12 02:27:44 +0000526 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000527 from stdout, or a traceback in case of exception). `want` ends
528 with a newline unless it's empty, in which case it's an empty
529 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000530
Edward Lopera6b68322004-08-26 00:05:43 +0000531 - exc_msg: The exception message generated by the example, if
532 the example is expected to generate an exception; or `None` if
533 it is not expected to generate an exception. This exception
534 message is compared against the return value of
535 `traceback.format_exception_only()`. `exc_msg` ends with a
536 newline unless it's `None`. The constructor adds a newline
537 if needed.
538
Edward Loper74bca7a2004-08-12 02:27:44 +0000539 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000540 this Example where the Example begins. This line number is
541 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000542
543 - indent: The example's indentation in the DocTest string.
544 I.e., the number of space characters that preceed the
545 example's first prompt.
546
547 - options: A dictionary mapping from option flags to True or
548 False, which is used to override default options for this
549 example. Any option flags not contained in this dictionary
550 are left at their default value (as specified by the
551 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000552 """
Edward Lopera6b68322004-08-26 00:05:43 +0000553 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
554 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000555 # Normalize inputs.
556 if not source.endswith('\n'):
557 source += '\n'
558 if want and not want.endswith('\n'):
559 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000560 if exc_msg is not None and not exc_msg.endswith('\n'):
561 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000562 # Store properties.
563 self.source = source
564 self.want = want
565 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000566 self.indent = indent
567 if options is None: options = {}
568 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000569 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000570
Tim Peters8485b562004-08-04 18:46:34 +0000571class DocTest:
572 """
573 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000574 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000575
Tim Peters8485b562004-08-04 18:46:34 +0000576 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000577
Tim Peters8485b562004-08-04 18:46:34 +0000578 - globs: The namespace (aka globals) that the examples should
579 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000580
Tim Peters8485b562004-08-04 18:46:34 +0000581 - name: A name identifying the DocTest (typically, the name of
582 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000583
Tim Peters8485b562004-08-04 18:46:34 +0000584 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000585 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000586
Tim Peters8485b562004-08-04 18:46:34 +0000587 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000588 begins, or `None` if the line number is unavailable. This
589 line number is zero-based, with respect to the beginning of
590 the file.
591
592 - docstring: The string that the examples were extracted from,
593 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000594 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000595 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000596 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000597 Create a new DocTest containing the given examples. The
598 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000599 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000600 assert not isinstance(examples, basestring), \
601 "DocTest no longer accepts str; use DocTestParser instead"
602 self.examples = examples
603 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000604 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000605 self.name = name
606 self.filename = filename
607 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000608
609 def __repr__(self):
610 if len(self.examples) == 0:
611 examples = 'no examples'
612 elif len(self.examples) == 1:
613 examples = '1 example'
614 else:
615 examples = '%d examples' % len(self.examples)
616 return ('<DocTest %s from %s:%s (%s)>' %
617 (self.name, self.filename, self.lineno, examples))
618
619
620 # This lets us sort tests by name:
621 def __cmp__(self, other):
622 if not isinstance(other, DocTest):
623 return -1
624 return cmp((self.name, self.filename, self.lineno, id(self)),
625 (other.name, other.filename, other.lineno, id(other)))
626
627######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000628## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000629######################################################################
630
Edward Lopera1ef6112004-08-09 16:14:41 +0000631class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000632 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000633 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000634 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000635 # This regular expression is used to find doctest examples in a
636 # string. It defines three groups: `source` is the source code
637 # (including leading indentation and prompts); `indent` is the
638 # indentation of the first (PS1) line of the source code; and
639 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000640 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000641 # Source consists of a PS1 line followed by zero or more PS2 lines.
642 (?P<source>
643 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
644 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
645 \n?
646 # Want consists of any non-blank lines that do not start with PS1.
647 (?P<want> (?:(?![ ]*$) # Not a blank line
648 (?![ ]*>>>) # Not a line starting with PS1
649 .*$\n? # But any other line
650 )*)
651 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000652
Edward Lopera6b68322004-08-26 00:05:43 +0000653 # A regular expression for handling `want` strings that contain
654 # expected exceptions. It divides `want` into three pieces:
655 # - the traceback header line (`hdr`)
656 # - the traceback stack (`stack`)
657 # - the exception message (`msg`), as generated by
658 # traceback.format_exception_only()
659 # `msg` may have multiple lines. We assume/require that the
660 # exception message is the first non-indented line starting with a word
661 # character following the traceback header line.
662 _EXCEPTION_RE = re.compile(r"""
663 # Grab the traceback header. Different versions of Python have
664 # said different things on the first traceback line.
665 ^(?P<hdr> Traceback\ \(
666 (?: most\ recent\ call\ last
667 | innermost\ last
668 ) \) :
669 )
670 \s* $ # toss trailing whitespace on the header.
671 (?P<stack> .*?) # don't blink: absorb stuff until...
672 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
673 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
674
Tim Peters7ea48dd2004-08-13 01:52:59 +0000675 # A callable returning a true value iff its argument is a blank line
676 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000677 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000678
Edward Loper00f8da72004-08-26 18:05:07 +0000679 def parse(self, string, name='<string>'):
680 """
681 Divide the given string into examples and intervening text,
682 and return them as a list of alternating Examples and strings.
683 Line numbers for the Examples are 0-based. The optional
684 argument `name` is a name identifying this string, and is only
685 used for error messages.
686 """
687 string = string.expandtabs()
688 # If all lines begin with the same indentation, then strip it.
689 min_indent = self._min_indent(string)
690 if min_indent > 0:
691 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
692
693 output = []
694 charno, lineno = 0, 0
695 # Find all doctest examples in the string:
Edward Loper2de91ba2004-08-27 02:07:46 +0000696 for m in self._EXAMPLE_RE.finditer(string):
Edward Loper00f8da72004-08-26 18:05:07 +0000697 # Add the pre-example text to `output`.
698 output.append(string[charno:m.start()])
699 # Update lineno (lines before this example)
700 lineno += string.count('\n', charno, m.start())
701 # Extract info from the regexp match.
702 (source, options, want, exc_msg) = \
703 self._parse_example(m, name, lineno)
704 # Create an Example, and add it to the list.
705 if not self._IS_BLANK_OR_COMMENT(source):
706 output.append( Example(source, want, exc_msg,
707 lineno=lineno,
708 indent=min_indent+len(m.group('indent')),
709 options=options) )
710 # Update lineno (lines inside this example)
711 lineno += string.count('\n', m.start(), m.end())
712 # Update charno.
713 charno = m.end()
714 # Add any remaining post-example text to `output`.
715 output.append(string[charno:])
716 return output
717
Edward Lopera1ef6112004-08-09 16:14:41 +0000718 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000719 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000720 Extract all doctest examples from the given string, and
721 collect them into a `DocTest` object.
722
723 `globs`, `name`, `filename`, and `lineno` are attributes for
724 the new `DocTest` object. See the documentation for `DocTest`
725 for more information.
726 """
727 return DocTest(self.get_examples(string, name), globs,
728 name, filename, lineno, string)
729
730 def get_examples(self, string, name='<string>'):
731 """
732 Extract all doctest examples from the given string, and return
733 them as a list of `Example` objects. Line numbers are
734 0-based, because it's most common in doctests that nothing
735 interesting appears on the same line as opening triple-quote,
736 and so the first interesting line is called \"line 1\" then.
737
738 The optional argument `name` is a name identifying this
739 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000740 """
Edward Loper00f8da72004-08-26 18:05:07 +0000741 return [x for x in self.parse(string, name)
742 if isinstance(x, Example)]
Edward Loper7c748462004-08-09 02:06:06 +0000743
Edward Loper74bca7a2004-08-12 02:27:44 +0000744 def _parse_example(self, m, name, lineno):
745 """
746 Given a regular expression match from `_EXAMPLE_RE` (`m`),
747 return a pair `(source, want)`, where `source` is the matched
748 example's source code (with prompts and indentation stripped);
749 and `want` is the example's expected output (with indentation
750 stripped).
751
752 `name` is the string's name, and `lineno` is the line number
753 where the example starts; both are used for error messages.
754 """
Edward Loper7c748462004-08-09 02:06:06 +0000755 # Get the example's indentation level.
756 indent = len(m.group('indent'))
757
758 # Divide source into lines; check that they're properly
759 # indented; and then strip their indentation & prompts.
760 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000761 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000762 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000763 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000764
Tim Petersc5049152004-08-22 17:34:58 +0000765 # Divide want into lines; check that it's properly indented; and
766 # then strip the indentation. Spaces before the last newline should
767 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000768 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000769 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000770 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
771 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000772 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000773 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000774 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000775
Edward Lopera6b68322004-08-26 00:05:43 +0000776 # If `want` contains a traceback message, then extract it.
777 m = self._EXCEPTION_RE.match(want)
778 if m:
779 exc_msg = m.group('msg')
780 else:
781 exc_msg = None
782
Edward Loper00f8da72004-08-26 18:05:07 +0000783 # Extract options from the source.
784 options = self._find_options(source, name, lineno)
785
786 return source, options, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000787
Edward Loper74bca7a2004-08-12 02:27:44 +0000788 # This regular expression looks for option directives in the
789 # source code of an example. Option directives are comments
790 # starting with "doctest:". Warning: this may give false
791 # positives for string-literals that contain the string
792 # "#doctest:". Eliminating these false positives would require
793 # actually parsing the string; but we limit them by ignoring any
794 # line containing "#doctest:" that is *followed* by a quote mark.
795 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
796 re.MULTILINE)
797
798 def _find_options(self, source, name, lineno):
799 """
800 Return a dictionary containing option overrides extracted from
801 option directives in the given source string.
802
803 `name` is the string's name, and `lineno` is the line number
804 where the example starts; both are used for error messages.
805 """
806 options = {}
807 # (note: with the current regexp, this will match at most once:)
808 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
809 option_strings = m.group(1).replace(',', ' ').split()
810 for option in option_strings:
811 if (option[0] not in '+-' or
812 option[1:] not in OPTIONFLAGS_BY_NAME):
813 raise ValueError('line %r of the doctest for %s '
814 'has an invalid option: %r' %
815 (lineno+1, name, option))
816 flag = OPTIONFLAGS_BY_NAME[option[1:]]
817 options[flag] = (option[0] == '+')
818 if options and self._IS_BLANK_OR_COMMENT(source):
819 raise ValueError('line %r of the doctest for %s has an option '
820 'directive on a line with no example: %r' %
821 (lineno, name, source))
822 return options
823
Edward Lopera5db6002004-08-12 02:41:30 +0000824 # This regular expression finds the indentation of every non-blank
825 # line in a string.
Edward Loper00f8da72004-08-26 18:05:07 +0000826 _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
Edward Lopera5db6002004-08-12 02:41:30 +0000827
828 def _min_indent(self, s):
829 "Return the minimum indentation of any non-blank line in `s`"
Edward Loper00f8da72004-08-26 18:05:07 +0000830 indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
831 if len(indents) > 0:
832 return min(indents)
Tim Petersdd0e4752004-08-09 03:31:56 +0000833 else:
Edward Loper00f8da72004-08-26 18:05:07 +0000834 return 0
Edward Loper7c748462004-08-09 02:06:06 +0000835
Edward Lopera1ef6112004-08-09 16:14:41 +0000836 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000837 """
838 Given the lines of a source string (including prompts and
839 leading indentation), check to make sure that every prompt is
840 followed by a space character. If any line is not followed by
841 a space character, then raise ValueError.
842 """
Edward Loper7c748462004-08-09 02:06:06 +0000843 for i, line in enumerate(lines):
844 if len(line) >= indent+4 and line[indent+3] != ' ':
845 raise ValueError('line %r of the docstring for %s '
846 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000847 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000848 line[indent:indent+3], line))
849
Edward Lopera1ef6112004-08-09 16:14:41 +0000850 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000851 """
852 Check that every line in the given list starts with the given
853 prefix; if any line does not, then raise a ValueError.
854 """
Edward Loper7c748462004-08-09 02:06:06 +0000855 for i, line in enumerate(lines):
856 if line and not line.startswith(prefix):
857 raise ValueError('line %r of the docstring for %s has '
858 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000859 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000860
861
862######################################################################
863## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000864######################################################################
865
866class DocTestFinder:
867 """
868 A class used to extract the DocTests that are relevant to a given
869 object, from its docstring and the docstrings of its contained
870 objects. Doctests can currently be extracted from the following
871 object types: modules, functions, classes, methods, staticmethods,
872 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000873 """
874
Edward Lopera1ef6112004-08-09 16:14:41 +0000875 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Peters958cc892004-09-13 14:53:28 +0000876 recurse=True, _namefilter=None, exclude_empty=True):
Tim Peters8485b562004-08-04 18:46:34 +0000877 """
878 Create a new doctest finder.
879
Edward Lopera1ef6112004-08-09 16:14:41 +0000880 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000881 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000882 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000883 signature for this factory function should match the signature
884 of the DocTest constructor.
885
Tim Peters8485b562004-08-04 18:46:34 +0000886 If the optional argument `recurse` is false, then `find` will
887 only examine the given object, and not any contained objects.
Edward Loper32ddbf72004-09-13 05:47:24 +0000888
Tim Peters958cc892004-09-13 14:53:28 +0000889 If the optional argument `exclude_empty` is false, then `find`
890 will include tests for objects with empty docstrings.
Tim Peters8485b562004-08-04 18:46:34 +0000891 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000892 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000893 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000894 self._recurse = recurse
Edward Loper32ddbf72004-09-13 05:47:24 +0000895 self._exclude_empty = exclude_empty
Tim Petersf727c6c2004-08-08 01:48:59 +0000896 # _namefilter is undocumented, and exists only for temporary backward-
897 # compatibility support of testmod's deprecated isprivate mess.
898 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000899
900 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000901 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000902 """
903 Return a list of the DocTests that are defined by the given
904 object's docstring, or by any of its contained objects'
905 docstrings.
906
907 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000908 the given object. If the module is not specified or is None, then
909 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000910 correct module. The object's module is used:
911
912 - As a default namespace, if `globs` is not specified.
913 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000914 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000915 - To find the name of the file containing the object.
916 - To help find the line number of the object within its
917 file.
918
Tim Petersf3f57472004-08-08 06:11:48 +0000919 Contained objects whose module does not match `module` are ignored.
920
921 If `module` is False, no attempt to find the module will be made.
922 This is obscure, of use mostly in tests: if `module` is False, or
923 is None but cannot be found automatically, then all objects are
924 considered to belong to the (non-existent) module, so all contained
925 objects will (recursively) be searched for doctests.
926
Tim Peters8485b562004-08-04 18:46:34 +0000927 The globals for each DocTest is formed by combining `globs`
928 and `extraglobs` (bindings in `extraglobs` override bindings
929 in `globs`). A new copy of the globals dictionary is created
930 for each DocTest. If `globs` is not specified, then it
931 defaults to the module's `__dict__`, if specified, or {}
932 otherwise. If `extraglobs` is not specified, then it defaults
933 to {}.
934
Tim Peters8485b562004-08-04 18:46:34 +0000935 """
936 # If name was not specified, then extract it from the object.
937 if name is None:
938 name = getattr(obj, '__name__', None)
939 if name is None:
940 raise ValueError("DocTestFinder.find: name must be given "
941 "when obj.__name__ doesn't exist: %r" %
942 (type(obj),))
943
944 # Find the module that contains the given object (if obj is
945 # a module, then module=obj.). Note: this may fail, in which
946 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000947 if module is False:
948 module = None
949 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000950 module = inspect.getmodule(obj)
951
952 # Read the module's source code. This is used by
953 # DocTestFinder._find_lineno to find the line number for a
954 # given object's docstring.
955 try:
956 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
957 source_lines = linecache.getlines(file)
958 if not source_lines:
959 source_lines = None
960 except TypeError:
961 source_lines = None
962
963 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000964 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000965 if module is None:
966 globs = {}
967 else:
968 globs = module.__dict__.copy()
969 else:
970 globs = globs.copy()
971 if extraglobs is not None:
972 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000973
Tim Peters8485b562004-08-04 18:46:34 +0000974 # Recursively expore `obj`, extracting DocTests.
975 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000976 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000977 return tests
978
979 def _filter(self, obj, prefix, base):
980 """
981 Return true if the given object should not be examined.
982 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000983 return (self._namefilter is not None and
984 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000985
986 def _from_module(self, module, object):
987 """
988 Return true if the given object is defined in the given
989 module.
990 """
991 if module is None:
992 return True
993 elif inspect.isfunction(object):
994 return module.__dict__ is object.func_globals
995 elif inspect.isclass(object):
996 return module.__name__ == object.__module__
997 elif inspect.getmodule(object) is not None:
998 return module is inspect.getmodule(object)
999 elif hasattr(object, '__module__'):
1000 return module.__name__ == object.__module__
1001 elif isinstance(object, property):
1002 return True # [XX] no way not be sure.
1003 else:
1004 raise ValueError("object must be a class or function")
1005
Tim Petersf3f57472004-08-08 06:11:48 +00001006 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +00001007 """
1008 Find tests for the given object and any contained objects, and
1009 add them to `tests`.
1010 """
1011 if self._verbose:
1012 print 'Finding tests in %s' % name
1013
1014 # If we've already processed this object, then ignore it.
1015 if id(obj) in seen:
1016 return
1017 seen[id(obj)] = 1
1018
1019 # Find a test for this object, and add it to the list of tests.
1020 test = self._get_test(obj, name, module, globs, source_lines)
1021 if test is not None:
1022 tests.append(test)
1023
1024 # Look for tests in a module's contained objects.
1025 if inspect.ismodule(obj) and self._recurse:
1026 for valname, val in obj.__dict__.items():
1027 # Check if this contained object should be ignored.
1028 if self._filter(val, name, valname):
1029 continue
1030 valname = '%s.%s' % (name, valname)
1031 # Recurse to functions & classes.
1032 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +00001033 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001034 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001035 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001036
1037 # Look for tests in a module's __test__ dictionary.
1038 if inspect.ismodule(obj) and self._recurse:
1039 for valname, val in getattr(obj, '__test__', {}).items():
1040 if not isinstance(valname, basestring):
1041 raise ValueError("DocTestFinder.find: __test__ keys "
1042 "must be strings: %r" %
1043 (type(valname),))
1044 if not (inspect.isfunction(val) or inspect.isclass(val) or
1045 inspect.ismethod(val) or inspect.ismodule(val) or
1046 isinstance(val, basestring)):
1047 raise ValueError("DocTestFinder.find: __test__ values "
1048 "must be strings, functions, methods, "
1049 "classes, or modules: %r" %
1050 (type(val),))
Tim Petersc5684782004-09-13 01:07:12 +00001051 valname = '%s.__test__.%s' % (name, valname)
Tim Peters8485b562004-08-04 18:46:34 +00001052 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001053 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001054
1055 # Look for tests in a class's contained objects.
1056 if inspect.isclass(obj) and self._recurse:
1057 for valname, val in obj.__dict__.items():
1058 # Check if this contained object should be ignored.
1059 if self._filter(val, name, valname):
1060 continue
1061 # Special handling for staticmethod/classmethod.
1062 if isinstance(val, staticmethod):
1063 val = getattr(obj, valname)
1064 if isinstance(val, classmethod):
1065 val = getattr(obj, valname).im_func
1066
1067 # Recurse to methods, properties, and nested classes.
1068 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001069 isinstance(val, property)) and
1070 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001071 valname = '%s.%s' % (name, valname)
1072 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001073 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001074
1075 def _get_test(self, obj, name, module, globs, source_lines):
1076 """
1077 Return a DocTest for the given object, if it defines a docstring;
1078 otherwise, return None.
1079 """
1080 # Extract the object's docstring. If it doesn't have one,
1081 # then return None (no test for this object).
1082 if isinstance(obj, basestring):
1083 docstring = obj
1084 else:
1085 try:
1086 if obj.__doc__ is None:
Edward Loper32ddbf72004-09-13 05:47:24 +00001087 docstring = ''
1088 else:
1089 docstring = str(obj.__doc__)
Tim Peters8485b562004-08-04 18:46:34 +00001090 except (TypeError, AttributeError):
Edward Loper32ddbf72004-09-13 05:47:24 +00001091 docstring = ''
Tim Peters8485b562004-08-04 18:46:34 +00001092
1093 # Find the docstring's location in the file.
1094 lineno = self._find_lineno(obj, source_lines)
1095
Edward Loper32ddbf72004-09-13 05:47:24 +00001096 # Don't bother if the docstring is empty.
1097 if self._exclude_empty and not docstring:
1098 return None
1099
Tim Peters8485b562004-08-04 18:46:34 +00001100 # Return a DocTest for this object.
1101 if module is None:
1102 filename = None
1103 else:
1104 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001105 if filename[-4:] in (".pyc", ".pyo"):
1106 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001107 return self._parser.get_doctest(docstring, globs, name,
1108 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001109
1110 def _find_lineno(self, obj, source_lines):
1111 """
1112 Return a line number of the given object's docstring. Note:
1113 this method assumes that the object has a docstring.
1114 """
1115 lineno = None
1116
1117 # Find the line number for modules.
1118 if inspect.ismodule(obj):
1119 lineno = 0
1120
1121 # Find the line number for classes.
1122 # Note: this could be fooled if a class is defined multiple
1123 # times in a single file.
1124 if inspect.isclass(obj):
1125 if source_lines is None:
1126 return None
1127 pat = re.compile(r'^\s*class\s*%s\b' %
1128 getattr(obj, '__name__', '-'))
1129 for i, line in enumerate(source_lines):
1130 if pat.match(line):
1131 lineno = i
1132 break
1133
1134 # Find the line number for functions & methods.
1135 if inspect.ismethod(obj): obj = obj.im_func
1136 if inspect.isfunction(obj): obj = obj.func_code
1137 if inspect.istraceback(obj): obj = obj.tb_frame
1138 if inspect.isframe(obj): obj = obj.f_code
1139 if inspect.iscode(obj):
1140 lineno = getattr(obj, 'co_firstlineno', None)-1
1141
1142 # Find the line number where the docstring starts. Assume
1143 # that it's the first line that begins with a quote mark.
1144 # Note: this could be fooled by a multiline function
1145 # signature, where a continuation line begins with a quote
1146 # mark.
1147 if lineno is not None:
1148 if source_lines is None:
1149 return lineno+1
1150 pat = re.compile('(^|.*:)\s*\w*("|\')')
1151 for lineno in range(lineno, len(source_lines)):
1152 if pat.match(source_lines[lineno]):
1153 return lineno
1154
1155 # We couldn't find the line number.
1156 return None
1157
1158######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001159## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001160######################################################################
1161
Tim Peters8485b562004-08-04 18:46:34 +00001162class DocTestRunner:
1163 """
1164 A class used to run DocTest test cases, and accumulate statistics.
1165 The `run` method is used to process a single DocTest case. It
1166 returns a tuple `(f, t)`, where `t` is the number of test cases
1167 tried, and `f` is the number of test cases that failed.
1168
1169 >>> tests = DocTestFinder().find(_TestClass)
1170 >>> runner = DocTestRunner(verbose=False)
1171 >>> for test in tests:
1172 ... print runner.run(test)
1173 (0, 2)
1174 (0, 1)
1175 (0, 2)
1176 (0, 2)
1177
1178 The `summarize` method prints a summary of all the test cases that
1179 have been run by the runner, and returns an aggregated `(f, t)`
1180 tuple:
1181
1182 >>> runner.summarize(verbose=1)
1183 4 items passed all tests:
1184 2 tests in _TestClass
1185 2 tests in _TestClass.__init__
1186 2 tests in _TestClass.get
1187 1 tests in _TestClass.square
1188 7 tests in 4 items.
1189 7 passed and 0 failed.
1190 Test passed.
1191 (0, 7)
1192
1193 The aggregated number of tried examples and failed examples is
1194 also available via the `tries` and `failures` attributes:
1195
1196 >>> runner.tries
1197 7
1198 >>> runner.failures
1199 0
1200
1201 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001202 by an `OutputChecker`. This comparison may be customized with a
1203 number of option flags; see the documentation for `testmod` for
1204 more information. If the option flags are insufficient, then the
1205 comparison may also be customized by passing a subclass of
1206 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001207
1208 The test runner's display output can be controlled in two ways.
1209 First, an output function (`out) can be passed to
1210 `TestRunner.run`; this function will be called with strings that
1211 should be displayed. It defaults to `sys.stdout.write`. If
1212 capturing the output is not sufficient, then the display output
1213 can be also customized by subclassing DocTestRunner, and
1214 overriding the methods `report_start`, `report_success`,
1215 `report_unexpected_exception`, and `report_failure`.
1216 """
1217 # This divider string is used to separate failure messages, and to
1218 # separate sections of the summary.
1219 DIVIDER = "*" * 70
1220
Edward Loper34fcb142004-08-09 02:45:41 +00001221 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001222 """
1223 Create a new test runner.
1224
Edward Loper34fcb142004-08-09 02:45:41 +00001225 Optional keyword arg `checker` is the `OutputChecker` that
1226 should be used to compare the expected outputs and actual
1227 outputs of doctest examples.
1228
Tim Peters8485b562004-08-04 18:46:34 +00001229 Optional keyword arg 'verbose' prints lots of stuff if true,
1230 only failures if false; by default, it's true iff '-v' is in
1231 sys.argv.
1232
1233 Optional argument `optionflags` can be used to control how the
1234 test runner compares expected output to actual output, and how
1235 it displays failures. See the documentation for `testmod` for
1236 more information.
1237 """
Edward Loper34fcb142004-08-09 02:45:41 +00001238 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001239 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001240 verbose = '-v' in sys.argv
1241 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001242 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001243 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001244
Tim Peters8485b562004-08-04 18:46:34 +00001245 # Keep track of the examples we've run.
1246 self.tries = 0
1247 self.failures = 0
1248 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001249
Tim Peters8485b562004-08-04 18:46:34 +00001250 # Create a fake output target for capturing doctest output.
1251 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001252
Tim Peters8485b562004-08-04 18:46:34 +00001253 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001254 # Reporting methods
1255 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001256
Tim Peters8485b562004-08-04 18:46:34 +00001257 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001258 """
Tim Peters8485b562004-08-04 18:46:34 +00001259 Report that the test runner is about to process the given
1260 example. (Only displays a message if verbose=True)
1261 """
1262 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001263 if example.want:
1264 out('Trying:\n' + _indent(example.source) +
1265 'Expecting:\n' + _indent(example.want))
1266 else:
1267 out('Trying:\n' + _indent(example.source) +
1268 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001269
Tim Peters8485b562004-08-04 18:46:34 +00001270 def report_success(self, out, test, example, got):
1271 """
1272 Report that the given example ran successfully. (Only
1273 displays a message if verbose=True)
1274 """
1275 if self._verbose:
1276 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001277
Tim Peters8485b562004-08-04 18:46:34 +00001278 def report_failure(self, out, test, example, got):
1279 """
1280 Report that the given example failed.
1281 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001282 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001283 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001284
Tim Peters8485b562004-08-04 18:46:34 +00001285 def report_unexpected_exception(self, out, test, example, exc_info):
1286 """
1287 Report that the given example raised an unexpected exception.
1288 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001289 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001290 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001291
Edward Loper8e4a34b2004-08-12 02:34:27 +00001292 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001293 out = [self.DIVIDER]
1294 if test.filename:
1295 if test.lineno is not None and example.lineno is not None:
1296 lineno = test.lineno + example.lineno + 1
1297 else:
1298 lineno = '?'
1299 out.append('File "%s", line %s, in %s' %
1300 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001301 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001302 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1303 out.append('Failed example:')
1304 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001305 out.append(_indent(source))
1306 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001307
Tim Peters8485b562004-08-04 18:46:34 +00001308 #/////////////////////////////////////////////////////////////////
1309 # DocTest Running
1310 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001311
Tim Peters8485b562004-08-04 18:46:34 +00001312 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001313 """
Tim Peters8485b562004-08-04 18:46:34 +00001314 Run the examples in `test`. Write the outcome of each example
1315 with one of the `DocTestRunner.report_*` methods, using the
1316 writer function `out`. `compileflags` is the set of compiler
1317 flags that should be used to execute examples. Return a tuple
1318 `(f, t)`, where `t` is the number of examples tried, and `f`
1319 is the number of examples that failed. The examples are run
1320 in the namespace `test.globs`.
1321 """
1322 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001323 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001324
1325 # Save the option flags (since option directives can be used
1326 # to modify them).
1327 original_optionflags = self.optionflags
1328
Tim Peters1fbf9c52004-09-04 17:21:02 +00001329 SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
1330
1331 check = self._checker.check_output
1332
Tim Peters8485b562004-08-04 18:46:34 +00001333 # Process each example.
Edward Loper2de91ba2004-08-27 02:07:46 +00001334 for examplenum, example in enumerate(test.examples):
1335
Edward Lopera89f88d2004-08-26 02:45:51 +00001336 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1337 # reporting after the first failure.
1338 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1339 failures > 0)
1340
Edward Loper74bca7a2004-08-12 02:27:44 +00001341 # Merge in the example's options.
1342 self.optionflags = original_optionflags
1343 if example.options:
1344 for (optionflag, val) in example.options.items():
1345 if val:
1346 self.optionflags |= optionflag
1347 else:
1348 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001349
1350 # Record that we started this example.
1351 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001352 if not quiet:
1353 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001354
Edward Loper2de91ba2004-08-27 02:07:46 +00001355 # Use a special filename for compile(), so we can retrieve
1356 # the source code during interactive debugging (see
1357 # __patched_linecache_getlines).
1358 filename = '<doctest %s[%d]>' % (test.name, examplenum)
1359
Tim Peters8485b562004-08-04 18:46:34 +00001360 # Run the example in the given context (globs), and record
1361 # any exception that gets raised. (But don't intercept
1362 # keyboard interrupts.)
1363 try:
Tim Peters208ca702004-08-09 04:12:36 +00001364 # Don't blink! This is where the user's code gets run.
Edward Loper2de91ba2004-08-27 02:07:46 +00001365 exec compile(example.source, filename, "single",
Tim Peters8485b562004-08-04 18:46:34 +00001366 compileflags, 1) in test.globs
Edward Loper2de91ba2004-08-27 02:07:46 +00001367 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001368 exception = None
1369 except KeyboardInterrupt:
1370 raise
1371 except:
1372 exception = sys.exc_info()
Edward Loper2de91ba2004-08-27 02:07:46 +00001373 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001374
Tim Peters208ca702004-08-09 04:12:36 +00001375 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001376 self._fakeout.truncate(0)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001377 outcome = FAILURE # guilty until proved innocent or insane
Tim Peters8485b562004-08-04 18:46:34 +00001378
1379 # If the example executed without raising any exceptions,
Tim Peters1fbf9c52004-09-04 17:21:02 +00001380 # verify its output.
Tim Peters8485b562004-08-04 18:46:34 +00001381 if exception is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001382 if check(example.want, got, self.optionflags):
1383 outcome = SUCCESS
Tim Peters8485b562004-08-04 18:46:34 +00001384
Tim Peters1fbf9c52004-09-04 17:21:02 +00001385 # The example raised an exception: check if it was expected.
Tim Peters8485b562004-08-04 18:46:34 +00001386 else:
1387 exc_info = sys.exc_info()
1388 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
Tim Peters1fbf9c52004-09-04 17:21:02 +00001389 if not quiet:
1390 got += _exception_traceback(exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001391
Tim Peters1fbf9c52004-09-04 17:21:02 +00001392 # If `example.exc_msg` is None, then we weren't expecting
1393 # an exception.
Edward Lopera6b68322004-08-26 00:05:43 +00001394 if example.exc_msg is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001395 outcome = BOOM
1396
1397 # We expected an exception: see whether it matches.
1398 elif check(example.exc_msg, exc_msg, self.optionflags):
1399 outcome = SUCCESS
1400
1401 # Another chance if they didn't care about the detail.
1402 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
1403 m1 = re.match(r'[^:]*:', example.exc_msg)
1404 m2 = re.match(r'[^:]*:', exc_msg)
1405 if m1 and m2 and check(m1.group(0), m2.group(0),
1406 self.optionflags):
1407 outcome = SUCCESS
1408
1409 # Report the outcome.
1410 if outcome is SUCCESS:
1411 if not quiet:
1412 self.report_success(out, test, example, got)
1413 elif outcome is FAILURE:
1414 if not quiet:
1415 self.report_failure(out, test, example, got)
1416 failures += 1
1417 elif outcome is BOOM:
1418 if not quiet:
1419 self.report_unexpected_exception(out, test, example,
1420 exc_info)
1421 failures += 1
1422 else:
1423 assert False, ("unknown outcome", outcome)
Tim Peters8485b562004-08-04 18:46:34 +00001424
1425 # Restore the option flags (in case they were modified)
1426 self.optionflags = original_optionflags
1427
1428 # Record and return the number of failures and tries.
1429 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001430 return failures, tries
1431
Tim Peters8485b562004-08-04 18:46:34 +00001432 def __record_outcome(self, test, f, t):
1433 """
1434 Record the fact that the given DocTest (`test`) generated `f`
1435 failures out of `t` tried examples.
1436 """
1437 f2, t2 = self._name2ft.get(test.name, (0,0))
1438 self._name2ft[test.name] = (f+f2, t+t2)
1439 self.failures += f
1440 self.tries += t
1441
Edward Loper2de91ba2004-08-27 02:07:46 +00001442 __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1443 r'(?P<name>[\w\.]+)'
1444 r'\[(?P<examplenum>\d+)\]>$')
1445 def __patched_linecache_getlines(self, filename):
1446 m = self.__LINECACHE_FILENAME_RE.match(filename)
1447 if m and m.group('name') == self.test.name:
1448 example = self.test.examples[int(m.group('examplenum'))]
1449 return example.source.splitlines(True)
1450 else:
1451 return self.save_linecache_getlines(filename)
1452
Tim Peters8485b562004-08-04 18:46:34 +00001453 def run(self, test, compileflags=None, out=None, clear_globs=True):
1454 """
1455 Run the examples in `test`, and display the results using the
1456 writer function `out`.
1457
1458 The examples are run in the namespace `test.globs`. If
1459 `clear_globs` is true (the default), then this namespace will
1460 be cleared after the test runs, to help with garbage
1461 collection. If you would like to examine the namespace after
1462 the test completes, then use `clear_globs=False`.
1463
1464 `compileflags` gives the set of flags that should be used by
1465 the Python compiler when running the examples. If not
1466 specified, then it will default to the set of future-import
1467 flags that apply to `globs`.
1468
1469 The output of each example is checked using
1470 `DocTestRunner.check_output`, and the results are formatted by
1471 the `DocTestRunner.report_*` methods.
1472 """
Edward Loper2de91ba2004-08-27 02:07:46 +00001473 self.test = test
1474
Tim Peters8485b562004-08-04 18:46:34 +00001475 if compileflags is None:
1476 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001477
Tim Peters6c542b72004-08-09 16:43:36 +00001478 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001479 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001480 out = save_stdout.write
1481 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001482
Edward Loper2de91ba2004-08-27 02:07:46 +00001483 # Patch pdb.set_trace to restore sys.stdout during interactive
1484 # debugging (so it's not still redirected to self._fakeout).
1485 # Note that the interactive output will go to *our*
1486 # save_stdout, even if that's not the real sys.stdout; this
1487 # allows us to write test cases for the set_trace behavior.
Tim Peters6c542b72004-08-09 16:43:36 +00001488 save_set_trace = pdb.set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001489 self.debugger = _OutputRedirectingPdb(save_stdout)
1490 self.debugger.reset()
1491 pdb.set_trace = self.debugger.set_trace
1492
1493 # Patch linecache.getlines, so we can see the example's source
1494 # when we're inside the debugger.
1495 self.save_linecache_getlines = linecache.getlines
1496 linecache.getlines = self.__patched_linecache_getlines
1497
Tim Peters8485b562004-08-04 18:46:34 +00001498 try:
Tim Peters8485b562004-08-04 18:46:34 +00001499 return self.__run(test, compileflags, out)
1500 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001501 sys.stdout = save_stdout
1502 pdb.set_trace = save_set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001503 linecache.getlines = self.save_linecache_getlines
Tim Peters8485b562004-08-04 18:46:34 +00001504 if clear_globs:
1505 test.globs.clear()
1506
1507 #/////////////////////////////////////////////////////////////////
1508 # Summarization
1509 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001510 def summarize(self, verbose=None):
1511 """
Tim Peters8485b562004-08-04 18:46:34 +00001512 Print a summary of all the test cases that have been run by
1513 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1514 the total number of failed examples, and `t` is the total
1515 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001516
Tim Peters8485b562004-08-04 18:46:34 +00001517 The optional `verbose` argument controls how detailed the
1518 summary is. If the verbosity is not specified, then the
1519 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001520 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001521 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001522 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001523 notests = []
1524 passed = []
1525 failed = []
1526 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001527 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001528 name, (f, t) = x
1529 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001530 totalt += t
1531 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001532 if t == 0:
1533 notests.append(name)
1534 elif f == 0:
1535 passed.append( (name, t) )
1536 else:
1537 failed.append(x)
1538 if verbose:
1539 if notests:
1540 print len(notests), "items had no tests:"
1541 notests.sort()
1542 for thing in notests:
1543 print " ", thing
1544 if passed:
1545 print len(passed), "items passed all tests:"
1546 passed.sort()
1547 for thing, count in passed:
1548 print " %3d tests in %s" % (count, thing)
1549 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001550 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001551 print len(failed), "items had failures:"
1552 failed.sort()
1553 for thing, (f, t) in failed:
1554 print " %3d of %3d in %s" % (f, t, thing)
1555 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001556 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001557 print totalt - totalf, "passed and", totalf, "failed."
1558 if totalf:
1559 print "***Test Failed***", totalf, "failures."
1560 elif verbose:
1561 print "Test passed."
1562 return totalf, totalt
1563
Tim Peters82076ef2004-09-13 00:52:51 +00001564 #/////////////////////////////////////////////////////////////////
1565 # Backward compatibility cruft to maintain doctest.master.
1566 #/////////////////////////////////////////////////////////////////
1567 def merge(self, other):
1568 d = self._name2ft
1569 for name, (f, t) in other._name2ft.items():
1570 if name in d:
1571 print "*** DocTestRunner.merge: '" + name + "' in both" \
1572 " testers; summing outcomes."
1573 f2, t2 = d[name]
1574 f = f + f2
1575 t = t + t2
1576 d[name] = f, t
1577
Edward Loper34fcb142004-08-09 02:45:41 +00001578class OutputChecker:
1579 """
1580 A class used to check the whether the actual output from a doctest
1581 example matches the expected output. `OutputChecker` defines two
1582 methods: `check_output`, which compares a given pair of outputs,
1583 and returns true if they match; and `output_difference`, which
1584 returns a string describing the differences between two outputs.
1585 """
1586 def check_output(self, want, got, optionflags):
1587 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001588 Return True iff the actual output from an example (`got`)
1589 matches the expected output (`want`). These strings are
1590 always considered to match if they are identical; but
1591 depending on what option flags the test runner is using,
1592 several non-exact match types are also possible. See the
1593 documentation for `TestRunner` for more information about
1594 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001595 """
1596 # Handle the common case first, for efficiency:
1597 # if they're string-identical, always return true.
1598 if got == want:
1599 return True
1600
1601 # The values True and False replaced 1 and 0 as the return
1602 # value for boolean comparisons in Python 2.3.
1603 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1604 if (got,want) == ("True\n", "1\n"):
1605 return True
1606 if (got,want) == ("False\n", "0\n"):
1607 return True
1608
1609 # <BLANKLINE> can be used as a special sequence to signify a
1610 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1611 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1612 # Replace <BLANKLINE> in want with a blank line.
1613 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1614 '', want)
1615 # If a line in got contains only spaces, then remove the
1616 # spaces.
1617 got = re.sub('(?m)^\s*?$', '', got)
1618 if got == want:
1619 return True
1620
1621 # This flag causes doctest to ignore any differences in the
1622 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001623 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001624 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001625 got = ' '.join(got.split())
1626 want = ' '.join(want.split())
1627 if got == want:
1628 return True
1629
1630 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001631 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001632 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001633 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001634 return True
1635
1636 # We didn't find any match; return false.
1637 return False
1638
Tim Petersc6cbab02004-08-22 19:43:28 +00001639 # Should we do a fancy diff?
1640 def _do_a_fancy_diff(self, want, got, optionflags):
1641 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001642 if not optionflags & (REPORT_UDIFF |
1643 REPORT_CDIFF |
1644 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001645 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001646
Tim Petersc6cbab02004-08-22 19:43:28 +00001647 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001648 # too hard ... or maybe not. In two real-life failures Tim saw,
1649 # a diff was a major help anyway, so this is commented out.
1650 # [todo] _ellipsis_match() knows which pieces do and don't match,
1651 # and could be the basis for a kick-ass diff in this case.
1652 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1653 ## return False
1654
Tim Petersc6cbab02004-08-22 19:43:28 +00001655 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001656 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001657 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001658 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001659
Tim Petersc6cbab02004-08-22 19:43:28 +00001660 # The other diff types need at least a few lines to be helpful.
1661 return want.count('\n') > 2 and got.count('\n') > 2
1662
Edward Loperca9111e2004-08-26 03:00:24 +00001663 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001664 """
1665 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001666 expected output for a given example (`example`) and the actual
1667 output (`got`). `optionflags` is the set of option flags used
1668 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001669 """
Edward Loperca9111e2004-08-26 03:00:24 +00001670 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001671 # If <BLANKLINE>s are being used, then replace blank lines
1672 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001673 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001674 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001675
Tim Peters5b799c12004-08-26 05:21:59 +00001676 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001677 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001678 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001679 want_lines = want.splitlines(True) # True == keep line ends
1680 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001681 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001682 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001683 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1684 diff = list(diff)[2:] # strip the diff header
1685 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001686 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001687 diff = difflib.context_diff(want_lines, got_lines, n=2)
1688 diff = list(diff)[2:] # strip the diff header
1689 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001690 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001691 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1692 diff = list(engine.compare(want_lines, got_lines))
1693 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001694 else:
1695 assert 0, 'Bad diff option'
1696 # Remove trailing whitespace on diff output.
1697 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001698 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001699
1700 # If we're not using diff, then simply list the expected
1701 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001702 if want and got:
1703 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1704 elif want:
1705 return 'Expected:\n%sGot nothing\n' % _indent(want)
1706 elif got:
1707 return 'Expected nothing\nGot:\n%s' % _indent(got)
1708 else:
1709 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001710
Tim Peters19397e52004-08-06 22:02:59 +00001711class DocTestFailure(Exception):
1712 """A DocTest example has failed in debugging mode.
1713
1714 The exception instance has variables:
1715
1716 - test: the DocTest object being run
1717
1718 - excample: the Example object that failed
1719
1720 - got: the actual output
1721 """
1722 def __init__(self, test, example, got):
1723 self.test = test
1724 self.example = example
1725 self.got = got
1726
1727 def __str__(self):
1728 return str(self.test)
1729
1730class UnexpectedException(Exception):
1731 """A DocTest example has encountered an unexpected exception
1732
1733 The exception instance has variables:
1734
1735 - test: the DocTest object being run
1736
1737 - excample: the Example object that failed
1738
1739 - exc_info: the exception info
1740 """
1741 def __init__(self, test, example, exc_info):
1742 self.test = test
1743 self.example = example
1744 self.exc_info = exc_info
1745
1746 def __str__(self):
1747 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001748
Tim Peters19397e52004-08-06 22:02:59 +00001749class DebugRunner(DocTestRunner):
1750 r"""Run doc tests but raise an exception as soon as there is a failure.
1751
1752 If an unexpected exception occurs, an UnexpectedException is raised.
1753 It contains the test, the example, and the original exception:
1754
1755 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001756 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1757 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001758 >>> try:
1759 ... runner.run(test)
1760 ... except UnexpectedException, failure:
1761 ... pass
1762
1763 >>> failure.test is test
1764 True
1765
1766 >>> failure.example.want
1767 '42\n'
1768
1769 >>> exc_info = failure.exc_info
1770 >>> raise exc_info[0], exc_info[1], exc_info[2]
1771 Traceback (most recent call last):
1772 ...
1773 KeyError
1774
1775 We wrap the original exception to give the calling application
1776 access to the test and example information.
1777
1778 If the output doesn't match, then a DocTestFailure is raised:
1779
Edward Lopera1ef6112004-08-09 16:14:41 +00001780 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001781 ... >>> x = 1
1782 ... >>> x
1783 ... 2
1784 ... ''', {}, 'foo', 'foo.py', 0)
1785
1786 >>> try:
1787 ... runner.run(test)
1788 ... except DocTestFailure, failure:
1789 ... pass
1790
1791 DocTestFailure objects provide access to the test:
1792
1793 >>> failure.test is test
1794 True
1795
1796 As well as to the example:
1797
1798 >>> failure.example.want
1799 '2\n'
1800
1801 and the actual output:
1802
1803 >>> failure.got
1804 '1\n'
1805
1806 If a failure or error occurs, the globals are left intact:
1807
1808 >>> del test.globs['__builtins__']
1809 >>> test.globs
1810 {'x': 1}
1811
Edward Lopera1ef6112004-08-09 16:14:41 +00001812 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001813 ... >>> x = 2
1814 ... >>> raise KeyError
1815 ... ''', {}, 'foo', 'foo.py', 0)
1816
1817 >>> runner.run(test)
1818 Traceback (most recent call last):
1819 ...
1820 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001821
Tim Peters19397e52004-08-06 22:02:59 +00001822 >>> del test.globs['__builtins__']
1823 >>> test.globs
1824 {'x': 2}
1825
1826 But the globals are cleared if there is no error:
1827
Edward Lopera1ef6112004-08-09 16:14:41 +00001828 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001829 ... >>> x = 2
1830 ... ''', {}, 'foo', 'foo.py', 0)
1831
1832 >>> runner.run(test)
1833 (0, 1)
1834
1835 >>> test.globs
1836 {}
1837
1838 """
1839
1840 def run(self, test, compileflags=None, out=None, clear_globs=True):
1841 r = DocTestRunner.run(self, test, compileflags, out, False)
1842 if clear_globs:
1843 test.globs.clear()
1844 return r
1845
1846 def report_unexpected_exception(self, out, test, example, exc_info):
1847 raise UnexpectedException(test, example, exc_info)
1848
1849 def report_failure(self, out, test, example, got):
1850 raise DocTestFailure(test, example, got)
1851
Tim Peters8485b562004-08-04 18:46:34 +00001852######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001853## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001854######################################################################
1855# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001856
Tim Peters82076ef2004-09-13 00:52:51 +00001857# For backward compatibility, a global instance of a DocTestRunner
1858# class, updated by testmod.
1859master = None
1860
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001861def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001862 report=True, optionflags=0, extraglobs=None,
Tim Peters958cc892004-09-13 14:53:28 +00001863 raise_on_error=False, exclude_empty=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001864 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters958cc892004-09-13 14:53:28 +00001865 report=True, optionflags=0, extraglobs=None, raise_on_error=False,
1866 exclude_empty=False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001867
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001868 Test examples in docstrings in functions and classes reachable
1869 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001870 with m.__doc__. Unless isprivate is specified, private names
1871 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001872
1873 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001874 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001875 function and class docstrings are tested even if the name is private;
1876 strings are tested directly, as if they were docstrings.
1877
1878 Return (#failures, #tests).
1879
1880 See doctest.__doc__ for an overview.
1881
1882 Optional keyword arg "name" gives the name of the module; by default
1883 use m.__name__.
1884
1885 Optional keyword arg "globs" gives a dict to be used as the globals
1886 when executing examples; by default, use m.__dict__. A copy of this
1887 dict is actually used for each docstring, so that each docstring's
1888 examples start with a clean slate.
1889
Tim Peters8485b562004-08-04 18:46:34 +00001890 Optional keyword arg "extraglobs" gives a dictionary that should be
1891 merged into the globals that are used to execute examples. By
1892 default, no extra globals are used. This is new in 2.4.
1893
Tim Peters8a7d2d52001-01-16 07:10:57 +00001894 Optional keyword arg "verbose" prints lots of stuff if true, prints
1895 only failures if false; by default, it's true iff "-v" is in sys.argv.
1896
Tim Peters8a7d2d52001-01-16 07:10:57 +00001897 Optional keyword arg "report" prints a summary at the end when true,
1898 else prints nothing at the end. In verbose mode, the summary is
1899 detailed, else very brief (in fact, empty if all tests passed).
1900
Tim Peters6ebe61f2003-06-27 20:48:05 +00001901 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001902 and defaults to 0. This is new in 2.3. Possible values (see the
1903 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001904
1905 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001906 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001907 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001908 ELLIPSIS
Edward Loper052d0cd2004-09-19 17:19:33 +00001909 IGNORE_EXCEPTION_DETAIL
Edward Loper71f55af2004-08-26 01:41:51 +00001910 REPORT_UDIFF
1911 REPORT_CDIFF
1912 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001913 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001914
1915 Optional keyword arg "raise_on_error" raises an exception on the
1916 first unexpected exception or failure. This allows failures to be
1917 post-mortem debugged.
1918
Tim Petersf727c6c2004-08-08 01:48:59 +00001919 Deprecated in Python 2.4:
1920 Optional keyword arg "isprivate" specifies a function used to
1921 determine whether a name is private. The default function is
1922 treat all functions as public. Optionally, "isprivate" can be
1923 set to doctest.is_private to skip over functions marked as private
1924 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001925
Tim Peters8a7d2d52001-01-16 07:10:57 +00001926 Advanced tomfoolery: testmod runs methods of a local instance of
1927 class doctest.Tester, then merges the results into (or creates)
1928 global Tester instance doctest.master. Methods of doctest.master
1929 can be called directly too, if you want to do something unusual.
1930 Passing report=0 to testmod is especially useful then, to delay
1931 displaying a summary. Invoke doctest.master.summarize(verbose)
1932 when you're done fiddling.
1933 """
Tim Peters82076ef2004-09-13 00:52:51 +00001934 global master
1935
Tim Petersf727c6c2004-08-08 01:48:59 +00001936 if isprivate is not None:
1937 warnings.warn("the isprivate argument is deprecated; "
1938 "examine DocTestFinder.find() lists instead",
1939 DeprecationWarning)
1940
Tim Peters8485b562004-08-04 18:46:34 +00001941 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001942 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001943 # DWA - m will still be None if this wasn't invoked from the command
1944 # line, in which case the following TypeError is about as good an error
1945 # as we should expect
1946 m = sys.modules.get('__main__')
1947
Tim Peters8485b562004-08-04 18:46:34 +00001948 # Check that we were actually given a module.
1949 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001950 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001951
1952 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001953 if name is None:
1954 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001955
1956 # Find, parse, and run all tests in the given module.
Tim Peters958cc892004-09-13 14:53:28 +00001957 finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty)
Tim Peters19397e52004-08-06 22:02:59 +00001958
1959 if raise_on_error:
1960 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1961 else:
1962 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1963
Tim Peters8485b562004-08-04 18:46:34 +00001964 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1965 runner.run(test)
1966
Tim Peters8a7d2d52001-01-16 07:10:57 +00001967 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001968 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001969
Tim Peters82076ef2004-09-13 00:52:51 +00001970 if master is None:
1971 master = runner
1972 else:
1973 master.merge(runner)
1974
Tim Peters8485b562004-08-04 18:46:34 +00001975 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001976
Edward Loper052d0cd2004-09-19 17:19:33 +00001977def testfile(filename, module_relative=True, name=None, package=None,
1978 globs=None, verbose=None, report=True, optionflags=0,
1979 extraglobs=None, raise_on_error=False):
1980 """
1981 Test examples in the given file. Return (#failures, #tests).
1982
1983 Optional keyword arg "module_relative" specifies how filenames
1984 should be interpreted:
1985
1986 - If "module_relative" is True (the default), then "filename"
1987 specifies a module-relative path. By default, this path is
1988 relative to the calling module's directory; but if the
1989 "package" argument is specified, then it is relative to that
1990 package. To ensure os-independence, "filename" should use
1991 "/" characters to separate path segments, and should not
1992 be an absolute path (i.e., it may not begin with "/").
1993
1994 - If "module_relative" is False, then "filename" specifies an
1995 os-specific path. The path may be absolute or relative (to
1996 the current working directory).
1997
1998 Optional keyword arg "name" gives the name of the file; by default
1999 use the file's name.
2000
2001 Optional keyword argument "package" is a Python package or the
2002 name of a Python package whose directory should be used as the
2003 base directory for a module relative filename. If no package is
2004 specified, then the calling module's directory is used as the base
2005 directory for module relative filenames. It is an error to
2006 specify "package" if "module_relative" is False.
2007
2008 Optional keyword arg "globs" gives a dict to be used as the globals
2009 when executing examples; by default, use {}. A copy of this dict
2010 is actually used for each docstring, so that each docstring's
2011 examples start with a clean slate.
2012
2013 Optional keyword arg "extraglobs" gives a dictionary that should be
2014 merged into the globals that are used to execute examples. By
2015 default, no extra globals are used.
2016
2017 Optional keyword arg "verbose" prints lots of stuff if true, prints
2018 only failures if false; by default, it's true iff "-v" is in sys.argv.
2019
2020 Optional keyword arg "report" prints a summary at the end when true,
2021 else prints nothing at the end. In verbose mode, the summary is
2022 detailed, else very brief (in fact, empty if all tests passed).
2023
2024 Optional keyword arg "optionflags" or's together module constants,
2025 and defaults to 0. Possible values (see the docs for details):
2026
2027 DONT_ACCEPT_TRUE_FOR_1
2028 DONT_ACCEPT_BLANKLINE
2029 NORMALIZE_WHITESPACE
2030 ELLIPSIS
2031 IGNORE_EXCEPTION_DETAIL
2032 REPORT_UDIFF
2033 REPORT_CDIFF
2034 REPORT_NDIFF
2035 REPORT_ONLY_FIRST_FAILURE
2036
2037 Optional keyword arg "raise_on_error" raises an exception on the
2038 first unexpected exception or failure. This allows failures to be
2039 post-mortem debugged.
2040
2041 Advanced tomfoolery: testmod runs methods of a local instance of
2042 class doctest.Tester, then merges the results into (or creates)
2043 global Tester instance doctest.master. Methods of doctest.master
2044 can be called directly too, if you want to do something unusual.
2045 Passing report=0 to testmod is especially useful then, to delay
2046 displaying a summary. Invoke doctest.master.summarize(verbose)
2047 when you're done fiddling.
2048 """
2049 global master
2050
2051 if package and not module_relative:
2052 raise ValueError("Package may only be specified for module-"
2053 "relative paths.")
2054
2055 # Relativize the path
2056 if module_relative:
2057 package = _normalize_module(package)
2058 filename = _module_relative_path(package, filename)
2059
2060 # If no name was given, then use the file's name.
2061 if name is None:
2062 name = os.path.split(filename)[-1]
2063
2064 # Assemble the globals.
2065 if globs is None:
2066 globs = {}
2067 else:
2068 globs = globs.copy()
2069 if extraglobs is not None:
2070 globs.update(extraglobs)
2071
2072 if raise_on_error:
2073 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
2074 else:
2075 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
2076
2077 # Read the file, convert it to a test, and run it.
2078 s = open(filename).read()
2079 test = DocTestParser().get_doctest(s, globs, name, filename, 0)
2080 runner.run(test)
2081
2082 if report:
2083 runner.summarize()
2084
2085 if master is None:
2086 master = runner
2087 else:
2088 master.merge(runner)
2089
2090 return runner.failures, runner.tries
2091
Tim Peters8485b562004-08-04 18:46:34 +00002092def run_docstring_examples(f, globs, verbose=False, name="NoName",
2093 compileflags=None, optionflags=0):
2094 """
2095 Test examples in the given object's docstring (`f`), using `globs`
2096 as globals. Optional argument `name` is used in failure messages.
2097 If the optional argument `verbose` is true, then generate output
2098 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00002099
Tim Peters8485b562004-08-04 18:46:34 +00002100 `compileflags` gives the set of flags that should be used by the
2101 Python compiler when running the examples. If not specified, then
2102 it will default to the set of future-import flags that apply to
2103 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00002104
Tim Peters8485b562004-08-04 18:46:34 +00002105 Optional keyword arg `optionflags` specifies options for the
2106 testing and output. See the documentation for `testmod` for more
2107 information.
2108 """
2109 # Find, parse, and run all tests in the given module.
2110 finder = DocTestFinder(verbose=verbose, recurse=False)
2111 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
2112 for test in finder.find(f, name, globs=globs):
2113 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00002114
Tim Peters8485b562004-08-04 18:46:34 +00002115######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002116## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00002117######################################################################
2118# This is provided only for backwards compatibility. It's not
2119# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00002120
Tim Peters8485b562004-08-04 18:46:34 +00002121class Tester:
2122 def __init__(self, mod=None, globs=None, verbose=None,
2123 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00002124
2125 warnings.warn("class Tester is deprecated; "
2126 "use class doctest.DocTestRunner instead",
2127 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00002128 if mod is None and globs is None:
2129 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters4be7a922004-09-12 22:39:46 +00002130 if mod is not None and not inspect.ismodule(mod):
Tim Peters8485b562004-08-04 18:46:34 +00002131 raise TypeError("Tester.__init__: mod must be a module; %r" %
2132 (mod,))
2133 if globs is None:
2134 globs = mod.__dict__
2135 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00002136
Tim Peters8485b562004-08-04 18:46:34 +00002137 self.verbose = verbose
2138 self.isprivate = isprivate
2139 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00002140 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00002141 self.testrunner = DocTestRunner(verbose=verbose,
2142 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00002143
Tim Peters8485b562004-08-04 18:46:34 +00002144 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00002145 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00002146 if self.verbose:
2147 print "Running string", name
2148 (f,t) = self.testrunner.run(test)
2149 if self.verbose:
2150 print f, "of", t, "examples failed in string", name
2151 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002152
Tim Petersf3f57472004-08-08 06:11:48 +00002153 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00002154 f = t = 0
2155 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00002156 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00002157 for test in tests:
2158 (f2, t2) = self.testrunner.run(test)
2159 (f,t) = (f+f2, t+t2)
2160 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002161
Tim Peters8485b562004-08-04 18:46:34 +00002162 def rundict(self, d, name, module=None):
2163 import new
2164 m = new.module(name)
2165 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00002166 if module is None:
2167 module = False
2168 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00002169
Tim Peters8485b562004-08-04 18:46:34 +00002170 def run__test__(self, d, name):
2171 import new
2172 m = new.module(name)
2173 m.__test__ = d
Tim Peters9661f9a2004-09-12 22:45:17 +00002174 return self.rundoc(m, name)
Tim Petersdb3756d2003-06-29 05:30:48 +00002175
Tim Peters8485b562004-08-04 18:46:34 +00002176 def summarize(self, verbose=None):
2177 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00002178
Tim Peters8485b562004-08-04 18:46:34 +00002179 def merge(self, other):
Tim Peters82076ef2004-09-13 00:52:51 +00002180 self.testrunner.merge(other.testrunner)
Tim Petersdb3756d2003-06-29 05:30:48 +00002181
Tim Peters8485b562004-08-04 18:46:34 +00002182######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002183## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002184######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002185
Jim Fultonf54bad42004-08-28 14:57:56 +00002186_unittest_reportflags = 0
Tim Peters38330fe2004-08-30 16:19:24 +00002187
Jim Fultonf54bad42004-08-28 14:57:56 +00002188def set_unittest_reportflags(flags):
Tim Peters38330fe2004-08-30 16:19:24 +00002189 """Sets the unittest option flags.
Jim Fultonf54bad42004-08-28 14:57:56 +00002190
2191 The old flag is returned so that a runner could restore the old
2192 value if it wished to:
2193
2194 >>> old = _unittest_reportflags
2195 >>> set_unittest_reportflags(REPORT_NDIFF |
2196 ... REPORT_ONLY_FIRST_FAILURE) == old
2197 True
2198
2199 >>> import doctest
2200 >>> doctest._unittest_reportflags == (REPORT_NDIFF |
2201 ... REPORT_ONLY_FIRST_FAILURE)
2202 True
Tim Petersdf7a2082004-08-29 00:38:17 +00002203
Jim Fultonf54bad42004-08-28 14:57:56 +00002204 Only reporting flags can be set:
2205
2206 >>> set_unittest_reportflags(ELLIPSIS)
2207 Traceback (most recent call last):
2208 ...
Tim Peters38330fe2004-08-30 16:19:24 +00002209 ValueError: ('Only reporting flags allowed', 8)
Jim Fultonf54bad42004-08-28 14:57:56 +00002210
2211 >>> set_unittest_reportflags(old) == (REPORT_NDIFF |
2212 ... REPORT_ONLY_FIRST_FAILURE)
2213 True
Jim Fultonf54bad42004-08-28 14:57:56 +00002214 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002215 global _unittest_reportflags
Tim Peters38330fe2004-08-30 16:19:24 +00002216
2217 if (flags & REPORTING_FLAGS) != flags:
2218 raise ValueError("Only reporting flags allowed", flags)
Jim Fultonf54bad42004-08-28 14:57:56 +00002219 old = _unittest_reportflags
2220 _unittest_reportflags = flags
2221 return old
Tim Petersdf7a2082004-08-29 00:38:17 +00002222
Jim Fultonf54bad42004-08-28 14:57:56 +00002223
Tim Peters19397e52004-08-06 22:02:59 +00002224class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002225
Edward Loper34fcb142004-08-09 02:45:41 +00002226 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2227 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002228
Jim Fultona643b652004-07-14 19:06:50 +00002229 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002230 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002231 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002232 self._dt_test = test
2233 self._dt_setUp = setUp
2234 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002235
Jim Fultona643b652004-07-14 19:06:50 +00002236 def setUp(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002237 test = self._dt_test
Tim Petersdf7a2082004-08-29 00:38:17 +00002238
Tim Peters19397e52004-08-06 22:02:59 +00002239 if self._dt_setUp is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002240 self._dt_setUp(test)
Jim Fultona643b652004-07-14 19:06:50 +00002241
2242 def tearDown(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002243 test = self._dt_test
2244
Tim Peters19397e52004-08-06 22:02:59 +00002245 if self._dt_tearDown is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002246 self._dt_tearDown(test)
2247
2248 test.globs.clear()
Jim Fultona643b652004-07-14 19:06:50 +00002249
2250 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002251 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002252 old = sys.stdout
2253 new = StringIO()
Jim Fultonf54bad42004-08-28 14:57:56 +00002254 optionflags = self._dt_optionflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002255
Tim Peters38330fe2004-08-30 16:19:24 +00002256 if not (optionflags & REPORTING_FLAGS):
Jim Fultonf54bad42004-08-28 14:57:56 +00002257 # The option flags don't include any reporting flags,
2258 # so add the default reporting flags
2259 optionflags |= _unittest_reportflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002260
Jim Fultonf54bad42004-08-28 14:57:56 +00002261 runner = DocTestRunner(optionflags=optionflags,
Edward Loper34fcb142004-08-09 02:45:41 +00002262 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002263
Jim Fultona643b652004-07-14 19:06:50 +00002264 try:
Tim Peters19397e52004-08-06 22:02:59 +00002265 runner.DIVIDER = "-"*70
Jim Fultonf54bad42004-08-28 14:57:56 +00002266 failures, tries = runner.run(
2267 test, out=new.write, clear_globs=False)
Jim Fultona643b652004-07-14 19:06:50 +00002268 finally:
2269 sys.stdout = old
2270
2271 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002272 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002273
Tim Peters19397e52004-08-06 22:02:59 +00002274 def format_failure(self, err):
2275 test = self._dt_test
2276 if test.lineno is None:
2277 lineno = 'unknown line number'
2278 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002279 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002280 lname = '.'.join(test.name.split('.')[-1:])
2281 return ('Failed doctest test for %s\n'
2282 ' File "%s", line %s, in %s\n\n%s'
2283 % (test.name, test.filename, lineno, lname, err)
2284 )
2285
2286 def debug(self):
2287 r"""Run the test case without results and without catching exceptions
2288
2289 The unit test framework includes a debug method on test cases
2290 and test suites to support post-mortem debugging. The test code
2291 is run in such a way that errors are not caught. This way a
2292 caller can catch the errors and initiate post-mortem debugging.
2293
2294 The DocTestCase provides a debug method that raises
2295 UnexpectedException errors if there is an unexepcted
2296 exception:
2297
Edward Lopera1ef6112004-08-09 16:14:41 +00002298 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002299 ... {}, 'foo', 'foo.py', 0)
2300 >>> case = DocTestCase(test)
2301 >>> try:
2302 ... case.debug()
2303 ... except UnexpectedException, failure:
2304 ... pass
2305
2306 The UnexpectedException contains the test, the example, and
2307 the original exception:
2308
2309 >>> failure.test is test
2310 True
2311
2312 >>> failure.example.want
2313 '42\n'
2314
2315 >>> exc_info = failure.exc_info
2316 >>> raise exc_info[0], exc_info[1], exc_info[2]
2317 Traceback (most recent call last):
2318 ...
2319 KeyError
2320
2321 If the output doesn't match, then a DocTestFailure is raised:
2322
Edward Lopera1ef6112004-08-09 16:14:41 +00002323 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002324 ... >>> x = 1
2325 ... >>> x
2326 ... 2
2327 ... ''', {}, 'foo', 'foo.py', 0)
2328 >>> case = DocTestCase(test)
2329
2330 >>> try:
2331 ... case.debug()
2332 ... except DocTestFailure, failure:
2333 ... pass
2334
2335 DocTestFailure objects provide access to the test:
2336
2337 >>> failure.test is test
2338 True
2339
2340 As well as to the example:
2341
2342 >>> failure.example.want
2343 '2\n'
2344
2345 and the actual output:
2346
2347 >>> failure.got
2348 '1\n'
2349
2350 """
2351
Jim Fultonf54bad42004-08-28 14:57:56 +00002352 self.setUp()
Edward Loper34fcb142004-08-09 02:45:41 +00002353 runner = DebugRunner(optionflags=self._dt_optionflags,
2354 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002355 runner.run(self._dt_test)
Jim Fultonf54bad42004-08-28 14:57:56 +00002356 self.tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002357
2358 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002359 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002360
2361 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002362 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002363 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2364
2365 __str__ = __repr__
2366
2367 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002368 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002369
Jim Fultonf54bad42004-08-28 14:57:56 +00002370def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2371 **options):
Tim Peters8485b562004-08-04 18:46:34 +00002372 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002373 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002374
Tim Peters19397e52004-08-06 22:02:59 +00002375 This converts each documentation string in a module that
2376 contains doctest tests to a unittest test case. If any of the
2377 tests in a doc string fail, then the test case fails. An exception
2378 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002379 (sometimes approximate) line number.
2380
Tim Peters19397e52004-08-06 22:02:59 +00002381 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002382 can be either a module or a module name.
2383
2384 If no argument is given, the calling module is used.
Jim Fultonf54bad42004-08-28 14:57:56 +00002385
2386 A number of options may be provided as keyword arguments:
2387
2388 package
2389 The name of a Python package. Text-file paths will be
2390 interpreted relative to the directory containing this package.
2391 The package may be supplied as a package object or as a dotted
2392 package name.
2393
2394 setUp
2395 The name of a set-up function. This is called before running the
2396 tests in each file. The setUp function will be passed a DocTest
2397 object. The setUp function can access the test globals as the
2398 globs attribute of the test passed.
2399
2400 tearDown
2401 The name of a tear-down function. This is called after running the
2402 tests in each file. The tearDown function will be passed a DocTest
2403 object. The tearDown function can access the test globals as the
2404 globs attribute of the test passed.
2405
2406 globs
2407 A dictionary containing initial global variables for the tests.
2408
2409 optionflags
2410 A set of doctest option flags expressed as an integer.
Jim Fultona643b652004-07-14 19:06:50 +00002411 """
Jim Fultona643b652004-07-14 19:06:50 +00002412
Tim Peters8485b562004-08-04 18:46:34 +00002413 if test_finder is None:
2414 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002415
Tim Peters19397e52004-08-06 22:02:59 +00002416 module = _normalize_module(module)
2417 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2418 if globs is None:
2419 globs = module.__dict__
Jim Fultonf54bad42004-08-28 14:57:56 +00002420 if not tests:
2421 # Why do we want to do this? Because it reveals a bug that might
2422 # otherwise be hidden.
Tim Peters19397e52004-08-06 22:02:59 +00002423 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002424
2425 tests.sort()
2426 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002427 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002428 if len(test.examples) == 0:
2429 continue
Tim Peters8485b562004-08-04 18:46:34 +00002430 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002431 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002432 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002433 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002434 test.filename = filename
Jim Fultonf54bad42004-08-28 14:57:56 +00002435 suite.addTest(DocTestCase(test, **options))
Tim Peters19397e52004-08-06 22:02:59 +00002436
2437 return suite
2438
2439class DocFileCase(DocTestCase):
2440
2441 def id(self):
2442 return '_'.join(self._dt_test.name.split('.'))
2443
2444 def __repr__(self):
2445 return self._dt_test.filename
2446 __str__ = __repr__
2447
2448 def format_failure(self, err):
2449 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2450 % (self._dt_test.name, self._dt_test.filename, err)
2451 )
2452
Edward Loper052d0cd2004-09-19 17:19:33 +00002453def DocFileTest(path, module_relative=True, package=None,
2454 globs=None, **options):
Tim Peters19397e52004-08-06 22:02:59 +00002455 if globs is None:
2456 globs = {}
2457
Edward Loper052d0cd2004-09-19 17:19:33 +00002458 if package and not module_relative:
2459 raise ValueError("Package may only be specified for module-"
2460 "relative paths.")
2461
2462 # Relativize the path.
2463 if module_relative:
2464 package = _normalize_module(package)
2465 path = _module_relative_path(package, path)
Tim Peters19397e52004-08-06 22:02:59 +00002466
Edward Loper052d0cd2004-09-19 17:19:33 +00002467 # Find the file and read it.
2468 name = os.path.split(path)[-1]
2469
2470 doc = open(path).read()
2471
2472 # Convert it to a test, and wrap it in a DocFileCase.
2473 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Jim Fultonf54bad42004-08-28 14:57:56 +00002474 return DocFileCase(test, **options)
Tim Peters19397e52004-08-06 22:02:59 +00002475
2476def DocFileSuite(*paths, **kw):
Edward Loper052d0cd2004-09-19 17:19:33 +00002477 """A unittest suite for one or more doctest files.
2478
2479 The path to each doctest file is given as a string; the
2480 interpretation of that string depends on the keyword argument
2481 "module_relative".
Tim Peters19397e52004-08-06 22:02:59 +00002482
2483 A number of options may be provided as keyword arguments:
2484
Edward Loper052d0cd2004-09-19 17:19:33 +00002485 module_relative
2486 If "module_relative" is True, then the given file paths are
2487 interpreted as os-independent module-relative paths. By
2488 default, these paths are relative to the calling module's
2489 directory; but if the "package" argument is specified, then
2490 they are relative to that package. To ensure os-independence,
2491 "filename" should use "/" characters to separate path
2492 segments, and may not be an absolute path (i.e., it may not
2493 begin with "/").
2494
2495 If "module_relative" is False, then the given file paths are
2496 interpreted as os-specific paths. These paths may be absolute
2497 or relative (to the current working directory).
2498
Tim Peters19397e52004-08-06 22:02:59 +00002499 package
Edward Loper052d0cd2004-09-19 17:19:33 +00002500 A Python package or the name of a Python package whose directory
2501 should be used as the base directory for module relative paths.
2502 If "package" is not specified, then the calling module's
2503 directory is used as the base directory for module relative
2504 filenames. It is an error to specify "package" if
2505 "module_relative" is False.
Tim Peters19397e52004-08-06 22:02:59 +00002506
2507 setUp
2508 The name of a set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002509 tests in each file. The setUp function will be passed a DocTest
2510 object. The setUp function can access the test globals as the
2511 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002512
2513 tearDown
2514 The name of a tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002515 tests in each file. The tearDown function will be passed a DocTest
2516 object. The tearDown function can access the test globals as the
2517 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002518
2519 globs
2520 A dictionary containing initial global variables for the tests.
Jim Fultonf54bad42004-08-28 14:57:56 +00002521
2522 optionflags
2523 A set of doctest option flags expressed as an integer.
Tim Peters19397e52004-08-06 22:02:59 +00002524 """
2525 suite = unittest.TestSuite()
2526
2527 # We do this here so that _normalize_module is called at the right
2528 # level. If it were called in DocFileTest, then this function
2529 # would be the caller and we might guess the package incorrectly.
Edward Loper052d0cd2004-09-19 17:19:33 +00002530 if kw.get('module_relative', True):
2531 kw['package'] = _normalize_module(kw.get('package'))
Tim Peters19397e52004-08-06 22:02:59 +00002532
2533 for path in paths:
2534 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002535
Tim Petersdb3756d2003-06-29 05:30:48 +00002536 return suite
2537
Tim Peters8485b562004-08-04 18:46:34 +00002538######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002539## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002540######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002541
Tim Peters19397e52004-08-06 22:02:59 +00002542def script_from_examples(s):
2543 r"""Extract script from text with examples.
2544
2545 Converts text with examples to a Python script. Example input is
2546 converted to regular code. Example output and all other words
2547 are converted to comments:
2548
2549 >>> text = '''
2550 ... Here are examples of simple math.
2551 ...
2552 ... Python has super accurate integer addition
2553 ...
2554 ... >>> 2 + 2
2555 ... 5
2556 ...
2557 ... And very friendly error messages:
2558 ...
2559 ... >>> 1/0
2560 ... To Infinity
2561 ... And
2562 ... Beyond
2563 ...
2564 ... You can use logic if you want:
2565 ...
2566 ... >>> if 0:
2567 ... ... blah
2568 ... ... blah
2569 ... ...
2570 ...
2571 ... Ho hum
2572 ... '''
2573
2574 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002575 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002576 #
Edward Lopera5db6002004-08-12 02:41:30 +00002577 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002578 #
2579 2 + 2
2580 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002581 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002582 #
Edward Lopera5db6002004-08-12 02:41:30 +00002583 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002584 #
2585 1/0
2586 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002587 ## To Infinity
2588 ## And
2589 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002590 #
Edward Lopera5db6002004-08-12 02:41:30 +00002591 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002592 #
2593 if 0:
2594 blah
2595 blah
Tim Peters19397e52004-08-06 22:02:59 +00002596 #
Edward Lopera5db6002004-08-12 02:41:30 +00002597 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002598 """
Edward Loper00f8da72004-08-26 18:05:07 +00002599 output = []
2600 for piece in DocTestParser().parse(s):
2601 if isinstance(piece, Example):
2602 # Add the example's source code (strip trailing NL)
2603 output.append(piece.source[:-1])
2604 # Add the expected output:
2605 want = piece.want
2606 if want:
2607 output.append('# Expected:')
2608 output += ['## '+l for l in want.split('\n')[:-1]]
2609 else:
2610 # Add non-example text.
2611 output += [_comment_line(l)
2612 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002613
Edward Loper00f8da72004-08-26 18:05:07 +00002614 # Trim junk on both ends.
2615 while output and output[-1] == '#':
2616 output.pop()
2617 while output and output[0] == '#':
2618 output.pop(0)
2619 # Combine the output, and return it.
2620 return '\n'.join(output)
Tim Petersdb3756d2003-06-29 05:30:48 +00002621
2622def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002623 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002624
2625 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002626 test to be debugged and the name (within the module) of the object
2627 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002628 """
Tim Peters8485b562004-08-04 18:46:34 +00002629 module = _normalize_module(module)
2630 tests = DocTestFinder().find(module)
2631 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002632 if not test:
2633 raise ValueError(name, "not found in tests")
2634 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002635 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002636 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002637
Jim Fultona643b652004-07-14 19:06:50 +00002638def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002639 """Debug a single doctest docstring, in argument `src`'"""
2640 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002641 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002642
Jim Fultona643b652004-07-14 19:06:50 +00002643def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002644 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002645 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002646
Tim Petersb6a04d62004-08-23 21:37:56 +00002647 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2648 # docs say, a file so created cannot be opened by name a second time
2649 # on modern Windows boxes, and execfile() needs to open it.
2650 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002651 f = open(srcfilename, 'w')
2652 f.write(src)
2653 f.close()
2654
Tim Petersb6a04d62004-08-23 21:37:56 +00002655 try:
2656 if globs:
2657 globs = globs.copy()
2658 else:
2659 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002660
Tim Petersb6a04d62004-08-23 21:37:56 +00002661 if pm:
2662 try:
2663 execfile(srcfilename, globs, globs)
2664 except:
2665 print sys.exc_info()[1]
2666 pdb.post_mortem(sys.exc_info()[2])
2667 else:
2668 # Note that %r is vital here. '%s' instead can, e.g., cause
2669 # backslashes to get treated as metacharacters on Windows.
2670 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2671
2672 finally:
2673 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002674
Jim Fultona643b652004-07-14 19:06:50 +00002675def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002676 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002677
2678 Provide the module (or dotted name of the module) containing the
2679 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002680 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002681 """
Tim Peters8485b562004-08-04 18:46:34 +00002682 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002683 testsrc = testsource(module, name)
2684 debug_script(testsrc, pm, module.__dict__)
2685
Tim Peters8485b562004-08-04 18:46:34 +00002686######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002687## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002688######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002689class _TestClass:
2690 """
2691 A pointless class, for sanity-checking of docstring testing.
2692
2693 Methods:
2694 square()
2695 get()
2696
2697 >>> _TestClass(13).get() + _TestClass(-12).get()
2698 1
2699 >>> hex(_TestClass(13).square().get())
2700 '0xa9'
2701 """
2702
2703 def __init__(self, val):
2704 """val -> _TestClass object with associated value val.
2705
2706 >>> t = _TestClass(123)
2707 >>> print t.get()
2708 123
2709 """
2710
2711 self.val = val
2712
2713 def square(self):
2714 """square() -> square TestClass's associated value
2715
2716 >>> _TestClass(13).square().get()
2717 169
2718 """
2719
2720 self.val = self.val ** 2
2721 return self
2722
2723 def get(self):
2724 """get() -> return TestClass's associated value.
2725
2726 >>> x = _TestClass(-42)
2727 >>> print x.get()
2728 -42
2729 """
2730
2731 return self.val
2732
2733__test__ = {"_TestClass": _TestClass,
2734 "string": r"""
2735 Example of a string object, searched as-is.
2736 >>> x = 1; y = 2
2737 >>> x + y, x * y
2738 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002739 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002740
Tim Peters6ebe61f2003-06-27 20:48:05 +00002741 "bool-int equivalence": r"""
2742 In 2.2, boolean expressions displayed
2743 0 or 1. By default, we still accept
2744 them. This can be disabled by passing
2745 DONT_ACCEPT_TRUE_FOR_1 to the new
2746 optionflags argument.
2747 >>> 4 == 4
2748 1
2749 >>> 4 == 4
2750 True
2751 >>> 4 > 4
2752 0
2753 >>> 4 > 4
2754 False
2755 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002756
Tim Peters8485b562004-08-04 18:46:34 +00002757 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002758 Blank lines can be marked with <BLANKLINE>:
2759 >>> print 'foo\n\nbar\n'
2760 foo
2761 <BLANKLINE>
2762 bar
2763 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002764 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002765
2766 "ellipsis": r"""
2767 If the ellipsis flag is used, then '...' can be used to
2768 elide substrings in the desired output:
2769 >>> print range(1000) #doctest: +ELLIPSIS
2770 [0, 1, 2, ..., 999]
2771 """,
2772
2773 "whitespace normalization": r"""
2774 If the whitespace normalization flag is used, then
2775 differences in whitespace are ignored.
2776 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2777 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2778 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2779 27, 28, 29]
2780 """,
2781 }
Tim Peters8485b562004-08-04 18:46:34 +00002782
Tim Peters8a7d2d52001-01-16 07:10:57 +00002783def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002784 r = unittest.TextTestRunner()
2785 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002786
2787if __name__ == "__main__":
2788 _test()