blob: b0e53d50071eb83202fc7a89efb7e6f9f02bd8e2 [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 Lopera2fc7ec2004-09-21 03:24:24 +0000482# [XX] Normalize with respect to os.path.pardir?
Edward Loper052d0cd2004-09-19 17:19:33 +0000483def _module_relative_path(module, path):
484 if not inspect.ismodule(module):
485 raise TypeError, 'Expected a module: %r' % module
486 if path.startswith('/'):
487 raise ValueError, 'Module-relative files may not have absolute paths'
488
489 # Find the base directory for the path.
490 if hasattr(module, '__file__'):
491 # A normal module/package
492 basedir = os.path.split(module.__file__)[0]
493 elif module.__name__ == '__main__':
494 # An interactive session.
495 if len(sys.argv)>0 and sys.argv[0] != '':
496 basedir = os.path.split(sys.argv[0])[0]
497 else:
498 basedir = os.curdir
499 else:
500 # A module w/o __file__ (this includes builtins)
501 raise ValueError("Can't resolve paths relative to the module " +
502 module + " (it has no __file__)")
503
504 # Combine the base directory and the path.
505 return os.path.join(basedir, *(path.split('/')))
506
Tim Peters8485b562004-08-04 18:46:34 +0000507######################################################################
508## 2. Example & DocTest
509######################################################################
510## - An "example" is a <source, want> pair, where "source" is a
511## fragment of source code, and "want" is the expected output for
512## "source." The Example class also includes information about
513## where the example was extracted from.
514##
Edward Lopera1ef6112004-08-09 16:14:41 +0000515## - A "doctest" is a collection of examples, typically extracted from
516## a string (such as an object's docstring). The DocTest class also
517## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000518
Tim Peters8485b562004-08-04 18:46:34 +0000519class Example:
520 """
521 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000522 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000523
Edward Loper74bca7a2004-08-12 02:27:44 +0000524 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000525 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000526
Edward Loper74bca7a2004-08-12 02:27:44 +0000527 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000528 from stdout, or a traceback in case of exception). `want` ends
529 with a newline unless it's empty, in which case it's an empty
530 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000531
Edward Lopera6b68322004-08-26 00:05:43 +0000532 - exc_msg: The exception message generated by the example, if
533 the example is expected to generate an exception; or `None` if
534 it is not expected to generate an exception. This exception
535 message is compared against the return value of
536 `traceback.format_exception_only()`. `exc_msg` ends with a
537 newline unless it's `None`. The constructor adds a newline
538 if needed.
539
Edward Loper74bca7a2004-08-12 02:27:44 +0000540 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000541 this Example where the Example begins. This line number is
542 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000543
544 - indent: The example's indentation in the DocTest string.
545 I.e., the number of space characters that preceed the
546 example's first prompt.
547
548 - options: A dictionary mapping from option flags to True or
549 False, which is used to override default options for this
550 example. Any option flags not contained in this dictionary
551 are left at their default value (as specified by the
552 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000553 """
Edward Lopera6b68322004-08-26 00:05:43 +0000554 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
555 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000556 # Normalize inputs.
557 if not source.endswith('\n'):
558 source += '\n'
559 if want and not want.endswith('\n'):
560 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000561 if exc_msg is not None and not exc_msg.endswith('\n'):
562 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000563 # Store properties.
564 self.source = source
565 self.want = want
566 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000567 self.indent = indent
568 if options is None: options = {}
569 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000570 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000571
Tim Peters8485b562004-08-04 18:46:34 +0000572class DocTest:
573 """
574 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000575 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000576
Tim Peters8485b562004-08-04 18:46:34 +0000577 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000578
Tim Peters8485b562004-08-04 18:46:34 +0000579 - globs: The namespace (aka globals) that the examples should
580 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000581
Tim Peters8485b562004-08-04 18:46:34 +0000582 - name: A name identifying the DocTest (typically, the name of
583 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000584
Tim Peters8485b562004-08-04 18:46:34 +0000585 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000586 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000587
Tim Peters8485b562004-08-04 18:46:34 +0000588 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000589 begins, or `None` if the line number is unavailable. This
590 line number is zero-based, with respect to the beginning of
591 the file.
592
593 - docstring: The string that the examples were extracted from,
594 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000595 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000596 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000597 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000598 Create a new DocTest containing the given examples. The
599 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000600 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000601 assert not isinstance(examples, basestring), \
602 "DocTest no longer accepts str; use DocTestParser instead"
603 self.examples = examples
604 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000605 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000606 self.name = name
607 self.filename = filename
608 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000609
610 def __repr__(self):
611 if len(self.examples) == 0:
612 examples = 'no examples'
613 elif len(self.examples) == 1:
614 examples = '1 example'
615 else:
616 examples = '%d examples' % len(self.examples)
617 return ('<DocTest %s from %s:%s (%s)>' %
618 (self.name, self.filename, self.lineno, examples))
619
620
621 # This lets us sort tests by name:
622 def __cmp__(self, other):
623 if not isinstance(other, DocTest):
624 return -1
625 return cmp((self.name, self.filename, self.lineno, id(self)),
626 (other.name, other.filename, other.lineno, id(other)))
627
628######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000629## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000630######################################################################
631
Edward Lopera1ef6112004-08-09 16:14:41 +0000632class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000633 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000634 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000635 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000636 # This regular expression is used to find doctest examples in a
637 # string. It defines three groups: `source` is the source code
638 # (including leading indentation and prompts); `indent` is the
639 # indentation of the first (PS1) line of the source code; and
640 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000641 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000642 # Source consists of a PS1 line followed by zero or more PS2 lines.
643 (?P<source>
644 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
645 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
646 \n?
647 # Want consists of any non-blank lines that do not start with PS1.
648 (?P<want> (?:(?![ ]*$) # Not a blank line
649 (?![ ]*>>>) # Not a line starting with PS1
650 .*$\n? # But any other line
651 )*)
652 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000653
Edward Lopera6b68322004-08-26 00:05:43 +0000654 # A regular expression for handling `want` strings that contain
655 # expected exceptions. It divides `want` into three pieces:
656 # - the traceback header line (`hdr`)
657 # - the traceback stack (`stack`)
658 # - the exception message (`msg`), as generated by
659 # traceback.format_exception_only()
660 # `msg` may have multiple lines. We assume/require that the
661 # exception message is the first non-indented line starting with a word
662 # character following the traceback header line.
663 _EXCEPTION_RE = re.compile(r"""
664 # Grab the traceback header. Different versions of Python have
665 # said different things on the first traceback line.
666 ^(?P<hdr> Traceback\ \(
667 (?: most\ recent\ call\ last
668 | innermost\ last
669 ) \) :
670 )
671 \s* $ # toss trailing whitespace on the header.
672 (?P<stack> .*?) # don't blink: absorb stuff until...
673 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
674 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
675
Tim Peters7ea48dd2004-08-13 01:52:59 +0000676 # A callable returning a true value iff its argument is a blank line
677 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000678 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000679
Edward Loper00f8da72004-08-26 18:05:07 +0000680 def parse(self, string, name='<string>'):
681 """
682 Divide the given string into examples and intervening text,
683 and return them as a list of alternating Examples and strings.
684 Line numbers for the Examples are 0-based. The optional
685 argument `name` is a name identifying this string, and is only
686 used for error messages.
687 """
688 string = string.expandtabs()
689 # If all lines begin with the same indentation, then strip it.
690 min_indent = self._min_indent(string)
691 if min_indent > 0:
692 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
693
694 output = []
695 charno, lineno = 0, 0
696 # Find all doctest examples in the string:
Edward Loper2de91ba2004-08-27 02:07:46 +0000697 for m in self._EXAMPLE_RE.finditer(string):
Edward Loper00f8da72004-08-26 18:05:07 +0000698 # Add the pre-example text to `output`.
699 output.append(string[charno:m.start()])
700 # Update lineno (lines before this example)
701 lineno += string.count('\n', charno, m.start())
702 # Extract info from the regexp match.
703 (source, options, want, exc_msg) = \
704 self._parse_example(m, name, lineno)
705 # Create an Example, and add it to the list.
706 if not self._IS_BLANK_OR_COMMENT(source):
707 output.append( Example(source, want, exc_msg,
708 lineno=lineno,
709 indent=min_indent+len(m.group('indent')),
710 options=options) )
711 # Update lineno (lines inside this example)
712 lineno += string.count('\n', m.start(), m.end())
713 # Update charno.
714 charno = m.end()
715 # Add any remaining post-example text to `output`.
716 output.append(string[charno:])
717 return output
718
Edward Lopera1ef6112004-08-09 16:14:41 +0000719 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000720 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000721 Extract all doctest examples from the given string, and
722 collect them into a `DocTest` object.
723
724 `globs`, `name`, `filename`, and `lineno` are attributes for
725 the new `DocTest` object. See the documentation for `DocTest`
726 for more information.
727 """
728 return DocTest(self.get_examples(string, name), globs,
729 name, filename, lineno, string)
730
731 def get_examples(self, string, name='<string>'):
732 """
733 Extract all doctest examples from the given string, and return
734 them as a list of `Example` objects. Line numbers are
735 0-based, because it's most common in doctests that nothing
736 interesting appears on the same line as opening triple-quote,
737 and so the first interesting line is called \"line 1\" then.
738
739 The optional argument `name` is a name identifying this
740 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000741 """
Edward Loper00f8da72004-08-26 18:05:07 +0000742 return [x for x in self.parse(string, name)
743 if isinstance(x, Example)]
Edward Loper7c748462004-08-09 02:06:06 +0000744
Edward Loper74bca7a2004-08-12 02:27:44 +0000745 def _parse_example(self, m, name, lineno):
746 """
747 Given a regular expression match from `_EXAMPLE_RE` (`m`),
748 return a pair `(source, want)`, where `source` is the matched
749 example's source code (with prompts and indentation stripped);
750 and `want` is the example's expected output (with indentation
751 stripped).
752
753 `name` is the string's name, and `lineno` is the line number
754 where the example starts; both are used for error messages.
755 """
Edward Loper7c748462004-08-09 02:06:06 +0000756 # Get the example's indentation level.
757 indent = len(m.group('indent'))
758
759 # Divide source into lines; check that they're properly
760 # indented; and then strip their indentation & prompts.
761 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000762 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000763 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000764 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000765
Tim Petersc5049152004-08-22 17:34:58 +0000766 # Divide want into lines; check that it's properly indented; and
767 # then strip the indentation. Spaces before the last newline should
768 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000769 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000770 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000771 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
772 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000773 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000774 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000775 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000776
Edward Lopera6b68322004-08-26 00:05:43 +0000777 # If `want` contains a traceback message, then extract it.
778 m = self._EXCEPTION_RE.match(want)
779 if m:
780 exc_msg = m.group('msg')
781 else:
782 exc_msg = None
783
Edward Loper00f8da72004-08-26 18:05:07 +0000784 # Extract options from the source.
785 options = self._find_options(source, name, lineno)
786
787 return source, options, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000788
Edward Loper74bca7a2004-08-12 02:27:44 +0000789 # This regular expression looks for option directives in the
790 # source code of an example. Option directives are comments
791 # starting with "doctest:". Warning: this may give false
792 # positives for string-literals that contain the string
793 # "#doctest:". Eliminating these false positives would require
794 # actually parsing the string; but we limit them by ignoring any
795 # line containing "#doctest:" that is *followed* by a quote mark.
796 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
797 re.MULTILINE)
798
799 def _find_options(self, source, name, lineno):
800 """
801 Return a dictionary containing option overrides extracted from
802 option directives in the given source string.
803
804 `name` is the string's name, and `lineno` is the line number
805 where the example starts; both are used for error messages.
806 """
807 options = {}
808 # (note: with the current regexp, this will match at most once:)
809 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
810 option_strings = m.group(1).replace(',', ' ').split()
811 for option in option_strings:
812 if (option[0] not in '+-' or
813 option[1:] not in OPTIONFLAGS_BY_NAME):
814 raise ValueError('line %r of the doctest for %s '
815 'has an invalid option: %r' %
816 (lineno+1, name, option))
817 flag = OPTIONFLAGS_BY_NAME[option[1:]]
818 options[flag] = (option[0] == '+')
819 if options and self._IS_BLANK_OR_COMMENT(source):
820 raise ValueError('line %r of the doctest for %s has an option '
821 'directive on a line with no example: %r' %
822 (lineno, name, source))
823 return options
824
Edward Lopera5db6002004-08-12 02:41:30 +0000825 # This regular expression finds the indentation of every non-blank
826 # line in a string.
Edward Loper00f8da72004-08-26 18:05:07 +0000827 _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
Edward Lopera5db6002004-08-12 02:41:30 +0000828
829 def _min_indent(self, s):
830 "Return the minimum indentation of any non-blank line in `s`"
Edward Loper00f8da72004-08-26 18:05:07 +0000831 indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
832 if len(indents) > 0:
833 return min(indents)
Tim Petersdd0e4752004-08-09 03:31:56 +0000834 else:
Edward Loper00f8da72004-08-26 18:05:07 +0000835 return 0
Edward Loper7c748462004-08-09 02:06:06 +0000836
Edward Lopera1ef6112004-08-09 16:14:41 +0000837 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000838 """
839 Given the lines of a source string (including prompts and
840 leading indentation), check to make sure that every prompt is
841 followed by a space character. If any line is not followed by
842 a space character, then raise ValueError.
843 """
Edward Loper7c748462004-08-09 02:06:06 +0000844 for i, line in enumerate(lines):
845 if len(line) >= indent+4 and line[indent+3] != ' ':
846 raise ValueError('line %r of the docstring for %s '
847 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000848 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000849 line[indent:indent+3], line))
850
Edward Lopera1ef6112004-08-09 16:14:41 +0000851 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000852 """
853 Check that every line in the given list starts with the given
854 prefix; if any line does not, then raise a ValueError.
855 """
Edward Loper7c748462004-08-09 02:06:06 +0000856 for i, line in enumerate(lines):
857 if line and not line.startswith(prefix):
858 raise ValueError('line %r of the docstring for %s has '
859 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000860 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000861
862
863######################################################################
864## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000865######################################################################
866
867class DocTestFinder:
868 """
869 A class used to extract the DocTests that are relevant to a given
870 object, from its docstring and the docstrings of its contained
871 objects. Doctests can currently be extracted from the following
872 object types: modules, functions, classes, methods, staticmethods,
873 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000874 """
875
Edward Lopera1ef6112004-08-09 16:14:41 +0000876 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Peters958cc892004-09-13 14:53:28 +0000877 recurse=True, _namefilter=None, exclude_empty=True):
Tim Peters8485b562004-08-04 18:46:34 +0000878 """
879 Create a new doctest finder.
880
Edward Lopera1ef6112004-08-09 16:14:41 +0000881 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000882 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000883 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000884 signature for this factory function should match the signature
885 of the DocTest constructor.
886
Tim Peters8485b562004-08-04 18:46:34 +0000887 If the optional argument `recurse` is false, then `find` will
888 only examine the given object, and not any contained objects.
Edward Loper32ddbf72004-09-13 05:47:24 +0000889
Tim Peters958cc892004-09-13 14:53:28 +0000890 If the optional argument `exclude_empty` is false, then `find`
891 will include tests for objects with empty docstrings.
Tim Peters8485b562004-08-04 18:46:34 +0000892 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000893 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000894 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000895 self._recurse = recurse
Edward Loper32ddbf72004-09-13 05:47:24 +0000896 self._exclude_empty = exclude_empty
Tim Petersf727c6c2004-08-08 01:48:59 +0000897 # _namefilter is undocumented, and exists only for temporary backward-
898 # compatibility support of testmod's deprecated isprivate mess.
899 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000900
901 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000902 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000903 """
904 Return a list of the DocTests that are defined by the given
905 object's docstring, or by any of its contained objects'
906 docstrings.
907
908 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000909 the given object. If the module is not specified or is None, then
910 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000911 correct module. The object's module is used:
912
913 - As a default namespace, if `globs` is not specified.
914 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000915 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000916 - To find the name of the file containing the object.
917 - To help find the line number of the object within its
918 file.
919
Tim Petersf3f57472004-08-08 06:11:48 +0000920 Contained objects whose module does not match `module` are ignored.
921
922 If `module` is False, no attempt to find the module will be made.
923 This is obscure, of use mostly in tests: if `module` is False, or
924 is None but cannot be found automatically, then all objects are
925 considered to belong to the (non-existent) module, so all contained
926 objects will (recursively) be searched for doctests.
927
Tim Peters8485b562004-08-04 18:46:34 +0000928 The globals for each DocTest is formed by combining `globs`
929 and `extraglobs` (bindings in `extraglobs` override bindings
930 in `globs`). A new copy of the globals dictionary is created
931 for each DocTest. If `globs` is not specified, then it
932 defaults to the module's `__dict__`, if specified, or {}
933 otherwise. If `extraglobs` is not specified, then it defaults
934 to {}.
935
Tim Peters8485b562004-08-04 18:46:34 +0000936 """
937 # If name was not specified, then extract it from the object.
938 if name is None:
939 name = getattr(obj, '__name__', None)
940 if name is None:
941 raise ValueError("DocTestFinder.find: name must be given "
942 "when obj.__name__ doesn't exist: %r" %
943 (type(obj),))
944
945 # Find the module that contains the given object (if obj is
946 # a module, then module=obj.). Note: this may fail, in which
947 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000948 if module is False:
949 module = None
950 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000951 module = inspect.getmodule(obj)
952
953 # Read the module's source code. This is used by
954 # DocTestFinder._find_lineno to find the line number for a
955 # given object's docstring.
956 try:
957 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
958 source_lines = linecache.getlines(file)
959 if not source_lines:
960 source_lines = None
961 except TypeError:
962 source_lines = None
963
964 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000965 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000966 if module is None:
967 globs = {}
968 else:
969 globs = module.__dict__.copy()
970 else:
971 globs = globs.copy()
972 if extraglobs is not None:
973 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000974
Tim Peters8485b562004-08-04 18:46:34 +0000975 # Recursively expore `obj`, extracting DocTests.
976 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000977 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000978 return tests
979
980 def _filter(self, obj, prefix, base):
981 """
982 Return true if the given object should not be examined.
983 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000984 return (self._namefilter is not None and
985 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000986
987 def _from_module(self, module, object):
988 """
989 Return true if the given object is defined in the given
990 module.
991 """
992 if module is None:
993 return True
994 elif inspect.isfunction(object):
995 return module.__dict__ is object.func_globals
996 elif inspect.isclass(object):
997 return module.__name__ == object.__module__
998 elif inspect.getmodule(object) is not None:
999 return module is inspect.getmodule(object)
1000 elif hasattr(object, '__module__'):
1001 return module.__name__ == object.__module__
1002 elif isinstance(object, property):
1003 return True # [XX] no way not be sure.
1004 else:
1005 raise ValueError("object must be a class or function")
1006
Tim Petersf3f57472004-08-08 06:11:48 +00001007 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +00001008 """
1009 Find tests for the given object and any contained objects, and
1010 add them to `tests`.
1011 """
1012 if self._verbose:
1013 print 'Finding tests in %s' % name
1014
1015 # If we've already processed this object, then ignore it.
1016 if id(obj) in seen:
1017 return
1018 seen[id(obj)] = 1
1019
1020 # Find a test for this object, and add it to the list of tests.
1021 test = self._get_test(obj, name, module, globs, source_lines)
1022 if test is not None:
1023 tests.append(test)
1024
1025 # Look for tests in a module's contained objects.
1026 if inspect.ismodule(obj) and self._recurse:
1027 for valname, val in obj.__dict__.items():
1028 # Check if this contained object should be ignored.
1029 if self._filter(val, name, valname):
1030 continue
1031 valname = '%s.%s' % (name, valname)
1032 # Recurse to functions & classes.
1033 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +00001034 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001035 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001036 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001037
1038 # Look for tests in a module's __test__ dictionary.
1039 if inspect.ismodule(obj) and self._recurse:
1040 for valname, val in getattr(obj, '__test__', {}).items():
1041 if not isinstance(valname, basestring):
1042 raise ValueError("DocTestFinder.find: __test__ keys "
1043 "must be strings: %r" %
1044 (type(valname),))
1045 if not (inspect.isfunction(val) or inspect.isclass(val) or
1046 inspect.ismethod(val) or inspect.ismodule(val) or
1047 isinstance(val, basestring)):
1048 raise ValueError("DocTestFinder.find: __test__ values "
1049 "must be strings, functions, methods, "
1050 "classes, or modules: %r" %
1051 (type(val),))
Tim Petersc5684782004-09-13 01:07:12 +00001052 valname = '%s.__test__.%s' % (name, valname)
Tim Peters8485b562004-08-04 18:46:34 +00001053 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001054 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001055
1056 # Look for tests in a class's contained objects.
1057 if inspect.isclass(obj) and self._recurse:
1058 for valname, val in obj.__dict__.items():
1059 # Check if this contained object should be ignored.
1060 if self._filter(val, name, valname):
1061 continue
1062 # Special handling for staticmethod/classmethod.
1063 if isinstance(val, staticmethod):
1064 val = getattr(obj, valname)
1065 if isinstance(val, classmethod):
1066 val = getattr(obj, valname).im_func
1067
1068 # Recurse to methods, properties, and nested classes.
1069 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001070 isinstance(val, property)) and
1071 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001072 valname = '%s.%s' % (name, valname)
1073 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001074 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001075
1076 def _get_test(self, obj, name, module, globs, source_lines):
1077 """
1078 Return a DocTest for the given object, if it defines a docstring;
1079 otherwise, return None.
1080 """
1081 # Extract the object's docstring. If it doesn't have one,
1082 # then return None (no test for this object).
1083 if isinstance(obj, basestring):
1084 docstring = obj
1085 else:
1086 try:
1087 if obj.__doc__ is None:
Edward Loper32ddbf72004-09-13 05:47:24 +00001088 docstring = ''
1089 else:
1090 docstring = str(obj.__doc__)
Tim Peters8485b562004-08-04 18:46:34 +00001091 except (TypeError, AttributeError):
Edward Loper32ddbf72004-09-13 05:47:24 +00001092 docstring = ''
Tim Peters8485b562004-08-04 18:46:34 +00001093
1094 # Find the docstring's location in the file.
1095 lineno = self._find_lineno(obj, source_lines)
1096
Edward Loper32ddbf72004-09-13 05:47:24 +00001097 # Don't bother if the docstring is empty.
1098 if self._exclude_empty and not docstring:
1099 return None
1100
Tim Peters8485b562004-08-04 18:46:34 +00001101 # Return a DocTest for this object.
1102 if module is None:
1103 filename = None
1104 else:
1105 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001106 if filename[-4:] in (".pyc", ".pyo"):
1107 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001108 return self._parser.get_doctest(docstring, globs, name,
1109 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001110
1111 def _find_lineno(self, obj, source_lines):
1112 """
1113 Return a line number of the given object's docstring. Note:
1114 this method assumes that the object has a docstring.
1115 """
1116 lineno = None
1117
1118 # Find the line number for modules.
1119 if inspect.ismodule(obj):
1120 lineno = 0
1121
1122 # Find the line number for classes.
1123 # Note: this could be fooled if a class is defined multiple
1124 # times in a single file.
1125 if inspect.isclass(obj):
1126 if source_lines is None:
1127 return None
1128 pat = re.compile(r'^\s*class\s*%s\b' %
1129 getattr(obj, '__name__', '-'))
1130 for i, line in enumerate(source_lines):
1131 if pat.match(line):
1132 lineno = i
1133 break
1134
1135 # Find the line number for functions & methods.
1136 if inspect.ismethod(obj): obj = obj.im_func
1137 if inspect.isfunction(obj): obj = obj.func_code
1138 if inspect.istraceback(obj): obj = obj.tb_frame
1139 if inspect.isframe(obj): obj = obj.f_code
1140 if inspect.iscode(obj):
1141 lineno = getattr(obj, 'co_firstlineno', None)-1
1142
1143 # Find the line number where the docstring starts. Assume
1144 # that it's the first line that begins with a quote mark.
1145 # Note: this could be fooled by a multiline function
1146 # signature, where a continuation line begins with a quote
1147 # mark.
1148 if lineno is not None:
1149 if source_lines is None:
1150 return lineno+1
1151 pat = re.compile('(^|.*:)\s*\w*("|\')')
1152 for lineno in range(lineno, len(source_lines)):
1153 if pat.match(source_lines[lineno]):
1154 return lineno
1155
1156 # We couldn't find the line number.
1157 return None
1158
1159######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001160## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001161######################################################################
1162
Tim Peters8485b562004-08-04 18:46:34 +00001163class DocTestRunner:
1164 """
1165 A class used to run DocTest test cases, and accumulate statistics.
1166 The `run` method is used to process a single DocTest case. It
1167 returns a tuple `(f, t)`, where `t` is the number of test cases
1168 tried, and `f` is the number of test cases that failed.
1169
1170 >>> tests = DocTestFinder().find(_TestClass)
1171 >>> runner = DocTestRunner(verbose=False)
1172 >>> for test in tests:
1173 ... print runner.run(test)
1174 (0, 2)
1175 (0, 1)
1176 (0, 2)
1177 (0, 2)
1178
1179 The `summarize` method prints a summary of all the test cases that
1180 have been run by the runner, and returns an aggregated `(f, t)`
1181 tuple:
1182
1183 >>> runner.summarize(verbose=1)
1184 4 items passed all tests:
1185 2 tests in _TestClass
1186 2 tests in _TestClass.__init__
1187 2 tests in _TestClass.get
1188 1 tests in _TestClass.square
1189 7 tests in 4 items.
1190 7 passed and 0 failed.
1191 Test passed.
1192 (0, 7)
1193
1194 The aggregated number of tried examples and failed examples is
1195 also available via the `tries` and `failures` attributes:
1196
1197 >>> runner.tries
1198 7
1199 >>> runner.failures
1200 0
1201
1202 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001203 by an `OutputChecker`. This comparison may be customized with a
1204 number of option flags; see the documentation for `testmod` for
1205 more information. If the option flags are insufficient, then the
1206 comparison may also be customized by passing a subclass of
1207 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001208
1209 The test runner's display output can be controlled in two ways.
1210 First, an output function (`out) can be passed to
1211 `TestRunner.run`; this function will be called with strings that
1212 should be displayed. It defaults to `sys.stdout.write`. If
1213 capturing the output is not sufficient, then the display output
1214 can be also customized by subclassing DocTestRunner, and
1215 overriding the methods `report_start`, `report_success`,
1216 `report_unexpected_exception`, and `report_failure`.
1217 """
1218 # This divider string is used to separate failure messages, and to
1219 # separate sections of the summary.
1220 DIVIDER = "*" * 70
1221
Edward Loper34fcb142004-08-09 02:45:41 +00001222 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001223 """
1224 Create a new test runner.
1225
Edward Loper34fcb142004-08-09 02:45:41 +00001226 Optional keyword arg `checker` is the `OutputChecker` that
1227 should be used to compare the expected outputs and actual
1228 outputs of doctest examples.
1229
Tim Peters8485b562004-08-04 18:46:34 +00001230 Optional keyword arg 'verbose' prints lots of stuff if true,
1231 only failures if false; by default, it's true iff '-v' is in
1232 sys.argv.
1233
1234 Optional argument `optionflags` can be used to control how the
1235 test runner compares expected output to actual output, and how
1236 it displays failures. See the documentation for `testmod` for
1237 more information.
1238 """
Edward Loper34fcb142004-08-09 02:45:41 +00001239 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001240 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001241 verbose = '-v' in sys.argv
1242 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001243 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001244 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001245
Tim Peters8485b562004-08-04 18:46:34 +00001246 # Keep track of the examples we've run.
1247 self.tries = 0
1248 self.failures = 0
1249 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001250
Tim Peters8485b562004-08-04 18:46:34 +00001251 # Create a fake output target for capturing doctest output.
1252 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001253
Tim Peters8485b562004-08-04 18:46:34 +00001254 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001255 # Reporting methods
1256 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001257
Tim Peters8485b562004-08-04 18:46:34 +00001258 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001259 """
Tim Peters8485b562004-08-04 18:46:34 +00001260 Report that the test runner is about to process the given
1261 example. (Only displays a message if verbose=True)
1262 """
1263 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001264 if example.want:
1265 out('Trying:\n' + _indent(example.source) +
1266 'Expecting:\n' + _indent(example.want))
1267 else:
1268 out('Trying:\n' + _indent(example.source) +
1269 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001270
Tim Peters8485b562004-08-04 18:46:34 +00001271 def report_success(self, out, test, example, got):
1272 """
1273 Report that the given example ran successfully. (Only
1274 displays a message if verbose=True)
1275 """
1276 if self._verbose:
1277 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001278
Tim Peters8485b562004-08-04 18:46:34 +00001279 def report_failure(self, out, test, example, got):
1280 """
1281 Report that the given example failed.
1282 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001283 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001284 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001285
Tim Peters8485b562004-08-04 18:46:34 +00001286 def report_unexpected_exception(self, out, test, example, exc_info):
1287 """
1288 Report that the given example raised an unexpected exception.
1289 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001290 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001291 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001292
Edward Loper8e4a34b2004-08-12 02:34:27 +00001293 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001294 out = [self.DIVIDER]
1295 if test.filename:
1296 if test.lineno is not None and example.lineno is not None:
1297 lineno = test.lineno + example.lineno + 1
1298 else:
1299 lineno = '?'
1300 out.append('File "%s", line %s, in %s' %
1301 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001302 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001303 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1304 out.append('Failed example:')
1305 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001306 out.append(_indent(source))
1307 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001308
Tim Peters8485b562004-08-04 18:46:34 +00001309 #/////////////////////////////////////////////////////////////////
1310 # DocTest Running
1311 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001312
Tim Peters8485b562004-08-04 18:46:34 +00001313 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001314 """
Tim Peters8485b562004-08-04 18:46:34 +00001315 Run the examples in `test`. Write the outcome of each example
1316 with one of the `DocTestRunner.report_*` methods, using the
1317 writer function `out`. `compileflags` is the set of compiler
1318 flags that should be used to execute examples. Return a tuple
1319 `(f, t)`, where `t` is the number of examples tried, and `f`
1320 is the number of examples that failed. The examples are run
1321 in the namespace `test.globs`.
1322 """
1323 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001324 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001325
1326 # Save the option flags (since option directives can be used
1327 # to modify them).
1328 original_optionflags = self.optionflags
1329
Tim Peters1fbf9c52004-09-04 17:21:02 +00001330 SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
1331
1332 check = self._checker.check_output
1333
Tim Peters8485b562004-08-04 18:46:34 +00001334 # Process each example.
Edward Loper2de91ba2004-08-27 02:07:46 +00001335 for examplenum, example in enumerate(test.examples):
1336
Edward Lopera89f88d2004-08-26 02:45:51 +00001337 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1338 # reporting after the first failure.
1339 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1340 failures > 0)
1341
Edward Loper74bca7a2004-08-12 02:27:44 +00001342 # Merge in the example's options.
1343 self.optionflags = original_optionflags
1344 if example.options:
1345 for (optionflag, val) in example.options.items():
1346 if val:
1347 self.optionflags |= optionflag
1348 else:
1349 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001350
1351 # Record that we started this example.
1352 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001353 if not quiet:
1354 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001355
Edward Loper2de91ba2004-08-27 02:07:46 +00001356 # Use a special filename for compile(), so we can retrieve
1357 # the source code during interactive debugging (see
1358 # __patched_linecache_getlines).
1359 filename = '<doctest %s[%d]>' % (test.name, examplenum)
1360
Tim Peters8485b562004-08-04 18:46:34 +00001361 # Run the example in the given context (globs), and record
1362 # any exception that gets raised. (But don't intercept
1363 # keyboard interrupts.)
1364 try:
Tim Peters208ca702004-08-09 04:12:36 +00001365 # Don't blink! This is where the user's code gets run.
Edward Loper2de91ba2004-08-27 02:07:46 +00001366 exec compile(example.source, filename, "single",
Tim Peters8485b562004-08-04 18:46:34 +00001367 compileflags, 1) in test.globs
Edward Loper2de91ba2004-08-27 02:07:46 +00001368 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001369 exception = None
1370 except KeyboardInterrupt:
1371 raise
1372 except:
1373 exception = sys.exc_info()
Edward Loper2de91ba2004-08-27 02:07:46 +00001374 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001375
Tim Peters208ca702004-08-09 04:12:36 +00001376 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001377 self._fakeout.truncate(0)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001378 outcome = FAILURE # guilty until proved innocent or insane
Tim Peters8485b562004-08-04 18:46:34 +00001379
1380 # If the example executed without raising any exceptions,
Tim Peters1fbf9c52004-09-04 17:21:02 +00001381 # verify its output.
Tim Peters8485b562004-08-04 18:46:34 +00001382 if exception is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001383 if check(example.want, got, self.optionflags):
1384 outcome = SUCCESS
Tim Peters8485b562004-08-04 18:46:34 +00001385
Tim Peters1fbf9c52004-09-04 17:21:02 +00001386 # The example raised an exception: check if it was expected.
Tim Peters8485b562004-08-04 18:46:34 +00001387 else:
1388 exc_info = sys.exc_info()
1389 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
Tim Peters1fbf9c52004-09-04 17:21:02 +00001390 if not quiet:
1391 got += _exception_traceback(exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001392
Tim Peters1fbf9c52004-09-04 17:21:02 +00001393 # If `example.exc_msg` is None, then we weren't expecting
1394 # an exception.
Edward Lopera6b68322004-08-26 00:05:43 +00001395 if example.exc_msg is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001396 outcome = BOOM
1397
1398 # We expected an exception: see whether it matches.
1399 elif check(example.exc_msg, exc_msg, self.optionflags):
1400 outcome = SUCCESS
1401
1402 # Another chance if they didn't care about the detail.
1403 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
1404 m1 = re.match(r'[^:]*:', example.exc_msg)
1405 m2 = re.match(r'[^:]*:', exc_msg)
1406 if m1 and m2 and check(m1.group(0), m2.group(0),
1407 self.optionflags):
1408 outcome = SUCCESS
1409
1410 # Report the outcome.
1411 if outcome is SUCCESS:
1412 if not quiet:
1413 self.report_success(out, test, example, got)
1414 elif outcome is FAILURE:
1415 if not quiet:
1416 self.report_failure(out, test, example, got)
1417 failures += 1
1418 elif outcome is BOOM:
1419 if not quiet:
1420 self.report_unexpected_exception(out, test, example,
1421 exc_info)
1422 failures += 1
1423 else:
1424 assert False, ("unknown outcome", outcome)
Tim Peters8485b562004-08-04 18:46:34 +00001425
1426 # Restore the option flags (in case they were modified)
1427 self.optionflags = original_optionflags
1428
1429 # Record and return the number of failures and tries.
1430 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001431 return failures, tries
1432
Tim Peters8485b562004-08-04 18:46:34 +00001433 def __record_outcome(self, test, f, t):
1434 """
1435 Record the fact that the given DocTest (`test`) generated `f`
1436 failures out of `t` tried examples.
1437 """
1438 f2, t2 = self._name2ft.get(test.name, (0,0))
1439 self._name2ft[test.name] = (f+f2, t+t2)
1440 self.failures += f
1441 self.tries += t
1442
Edward Loper2de91ba2004-08-27 02:07:46 +00001443 __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1444 r'(?P<name>[\w\.]+)'
1445 r'\[(?P<examplenum>\d+)\]>$')
1446 def __patched_linecache_getlines(self, filename):
1447 m = self.__LINECACHE_FILENAME_RE.match(filename)
1448 if m and m.group('name') == self.test.name:
1449 example = self.test.examples[int(m.group('examplenum'))]
1450 return example.source.splitlines(True)
1451 else:
1452 return self.save_linecache_getlines(filename)
1453
Tim Peters8485b562004-08-04 18:46:34 +00001454 def run(self, test, compileflags=None, out=None, clear_globs=True):
1455 """
1456 Run the examples in `test`, and display the results using the
1457 writer function `out`.
1458
1459 The examples are run in the namespace `test.globs`. If
1460 `clear_globs` is true (the default), then this namespace will
1461 be cleared after the test runs, to help with garbage
1462 collection. If you would like to examine the namespace after
1463 the test completes, then use `clear_globs=False`.
1464
1465 `compileflags` gives the set of flags that should be used by
1466 the Python compiler when running the examples. If not
1467 specified, then it will default to the set of future-import
1468 flags that apply to `globs`.
1469
1470 The output of each example is checked using
1471 `DocTestRunner.check_output`, and the results are formatted by
1472 the `DocTestRunner.report_*` methods.
1473 """
Edward Loper2de91ba2004-08-27 02:07:46 +00001474 self.test = test
1475
Tim Peters8485b562004-08-04 18:46:34 +00001476 if compileflags is None:
1477 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001478
Tim Peters6c542b72004-08-09 16:43:36 +00001479 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001480 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001481 out = save_stdout.write
1482 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001483
Edward Loper2de91ba2004-08-27 02:07:46 +00001484 # Patch pdb.set_trace to restore sys.stdout during interactive
1485 # debugging (so it's not still redirected to self._fakeout).
1486 # Note that the interactive output will go to *our*
1487 # save_stdout, even if that's not the real sys.stdout; this
1488 # allows us to write test cases for the set_trace behavior.
Tim Peters6c542b72004-08-09 16:43:36 +00001489 save_set_trace = pdb.set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001490 self.debugger = _OutputRedirectingPdb(save_stdout)
1491 self.debugger.reset()
1492 pdb.set_trace = self.debugger.set_trace
1493
1494 # Patch linecache.getlines, so we can see the example's source
1495 # when we're inside the debugger.
1496 self.save_linecache_getlines = linecache.getlines
1497 linecache.getlines = self.__patched_linecache_getlines
1498
Tim Peters8485b562004-08-04 18:46:34 +00001499 try:
Tim Peters8485b562004-08-04 18:46:34 +00001500 return self.__run(test, compileflags, out)
1501 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001502 sys.stdout = save_stdout
1503 pdb.set_trace = save_set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001504 linecache.getlines = self.save_linecache_getlines
Tim Peters8485b562004-08-04 18:46:34 +00001505 if clear_globs:
1506 test.globs.clear()
1507
1508 #/////////////////////////////////////////////////////////////////
1509 # Summarization
1510 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001511 def summarize(self, verbose=None):
1512 """
Tim Peters8485b562004-08-04 18:46:34 +00001513 Print a summary of all the test cases that have been run by
1514 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1515 the total number of failed examples, and `t` is the total
1516 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001517
Tim Peters8485b562004-08-04 18:46:34 +00001518 The optional `verbose` argument controls how detailed the
1519 summary is. If the verbosity is not specified, then the
1520 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001521 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001522 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001523 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001524 notests = []
1525 passed = []
1526 failed = []
1527 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001528 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001529 name, (f, t) = x
1530 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001531 totalt += t
1532 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001533 if t == 0:
1534 notests.append(name)
1535 elif f == 0:
1536 passed.append( (name, t) )
1537 else:
1538 failed.append(x)
1539 if verbose:
1540 if notests:
1541 print len(notests), "items had no tests:"
1542 notests.sort()
1543 for thing in notests:
1544 print " ", thing
1545 if passed:
1546 print len(passed), "items passed all tests:"
1547 passed.sort()
1548 for thing, count in passed:
1549 print " %3d tests in %s" % (count, thing)
1550 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001551 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001552 print len(failed), "items had failures:"
1553 failed.sort()
1554 for thing, (f, t) in failed:
1555 print " %3d of %3d in %s" % (f, t, thing)
1556 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001557 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001558 print totalt - totalf, "passed and", totalf, "failed."
1559 if totalf:
1560 print "***Test Failed***", totalf, "failures."
1561 elif verbose:
1562 print "Test passed."
1563 return totalf, totalt
1564
Tim Peters82076ef2004-09-13 00:52:51 +00001565 #/////////////////////////////////////////////////////////////////
1566 # Backward compatibility cruft to maintain doctest.master.
1567 #/////////////////////////////////////////////////////////////////
1568 def merge(self, other):
1569 d = self._name2ft
1570 for name, (f, t) in other._name2ft.items():
1571 if name in d:
1572 print "*** DocTestRunner.merge: '" + name + "' in both" \
1573 " testers; summing outcomes."
1574 f2, t2 = d[name]
1575 f = f + f2
1576 t = t + t2
1577 d[name] = f, t
1578
Edward Loper34fcb142004-08-09 02:45:41 +00001579class OutputChecker:
1580 """
1581 A class used to check the whether the actual output from a doctest
1582 example matches the expected output. `OutputChecker` defines two
1583 methods: `check_output`, which compares a given pair of outputs,
1584 and returns true if they match; and `output_difference`, which
1585 returns a string describing the differences between two outputs.
1586 """
1587 def check_output(self, want, got, optionflags):
1588 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001589 Return True iff the actual output from an example (`got`)
1590 matches the expected output (`want`). These strings are
1591 always considered to match if they are identical; but
1592 depending on what option flags the test runner is using,
1593 several non-exact match types are also possible. See the
1594 documentation for `TestRunner` for more information about
1595 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001596 """
1597 # Handle the common case first, for efficiency:
1598 # if they're string-identical, always return true.
1599 if got == want:
1600 return True
1601
1602 # The values True and False replaced 1 and 0 as the return
1603 # value for boolean comparisons in Python 2.3.
1604 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1605 if (got,want) == ("True\n", "1\n"):
1606 return True
1607 if (got,want) == ("False\n", "0\n"):
1608 return True
1609
1610 # <BLANKLINE> can be used as a special sequence to signify a
1611 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1612 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1613 # Replace <BLANKLINE> in want with a blank line.
1614 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1615 '', want)
1616 # If a line in got contains only spaces, then remove the
1617 # spaces.
1618 got = re.sub('(?m)^\s*?$', '', got)
1619 if got == want:
1620 return True
1621
1622 # This flag causes doctest to ignore any differences in the
1623 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001624 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001625 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001626 got = ' '.join(got.split())
1627 want = ' '.join(want.split())
1628 if got == want:
1629 return True
1630
1631 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001632 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001633 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001634 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001635 return True
1636
1637 # We didn't find any match; return false.
1638 return False
1639
Tim Petersc6cbab02004-08-22 19:43:28 +00001640 # Should we do a fancy diff?
1641 def _do_a_fancy_diff(self, want, got, optionflags):
1642 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001643 if not optionflags & (REPORT_UDIFF |
1644 REPORT_CDIFF |
1645 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001646 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001647
Tim Petersc6cbab02004-08-22 19:43:28 +00001648 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001649 # too hard ... or maybe not. In two real-life failures Tim saw,
1650 # a diff was a major help anyway, so this is commented out.
1651 # [todo] _ellipsis_match() knows which pieces do and don't match,
1652 # and could be the basis for a kick-ass diff in this case.
1653 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1654 ## return False
1655
Tim Petersc6cbab02004-08-22 19:43:28 +00001656 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001657 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001658 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001659 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001660
Tim Petersc6cbab02004-08-22 19:43:28 +00001661 # The other diff types need at least a few lines to be helpful.
1662 return want.count('\n') > 2 and got.count('\n') > 2
1663
Edward Loperca9111e2004-08-26 03:00:24 +00001664 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001665 """
1666 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001667 expected output for a given example (`example`) and the actual
1668 output (`got`). `optionflags` is the set of option flags used
1669 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001670 """
Edward Loperca9111e2004-08-26 03:00:24 +00001671 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001672 # If <BLANKLINE>s are being used, then replace blank lines
1673 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001674 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001675 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001676
Tim Peters5b799c12004-08-26 05:21:59 +00001677 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001678 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001679 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001680 want_lines = want.splitlines(True) # True == keep line ends
1681 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001682 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001683 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001684 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1685 diff = list(diff)[2:] # strip the diff header
1686 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001687 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001688 diff = difflib.context_diff(want_lines, got_lines, n=2)
1689 diff = list(diff)[2:] # strip the diff header
1690 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001691 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001692 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1693 diff = list(engine.compare(want_lines, got_lines))
1694 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001695 else:
1696 assert 0, 'Bad diff option'
1697 # Remove trailing whitespace on diff output.
1698 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001699 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001700
1701 # If we're not using diff, then simply list the expected
1702 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001703 if want and got:
1704 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1705 elif want:
1706 return 'Expected:\n%sGot nothing\n' % _indent(want)
1707 elif got:
1708 return 'Expected nothing\nGot:\n%s' % _indent(got)
1709 else:
1710 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001711
Tim Peters19397e52004-08-06 22:02:59 +00001712class DocTestFailure(Exception):
1713 """A DocTest example has failed in debugging mode.
1714
1715 The exception instance has variables:
1716
1717 - test: the DocTest object being run
1718
1719 - excample: the Example object that failed
1720
1721 - got: the actual output
1722 """
1723 def __init__(self, test, example, got):
1724 self.test = test
1725 self.example = example
1726 self.got = got
1727
1728 def __str__(self):
1729 return str(self.test)
1730
1731class UnexpectedException(Exception):
1732 """A DocTest example has encountered an unexpected exception
1733
1734 The exception instance has variables:
1735
1736 - test: the DocTest object being run
1737
1738 - excample: the Example object that failed
1739
1740 - exc_info: the exception info
1741 """
1742 def __init__(self, test, example, exc_info):
1743 self.test = test
1744 self.example = example
1745 self.exc_info = exc_info
1746
1747 def __str__(self):
1748 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001749
Tim Peters19397e52004-08-06 22:02:59 +00001750class DebugRunner(DocTestRunner):
1751 r"""Run doc tests but raise an exception as soon as there is a failure.
1752
1753 If an unexpected exception occurs, an UnexpectedException is raised.
1754 It contains the test, the example, and the original exception:
1755
1756 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001757 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1758 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001759 >>> try:
1760 ... runner.run(test)
1761 ... except UnexpectedException, failure:
1762 ... pass
1763
1764 >>> failure.test is test
1765 True
1766
1767 >>> failure.example.want
1768 '42\n'
1769
1770 >>> exc_info = failure.exc_info
1771 >>> raise exc_info[0], exc_info[1], exc_info[2]
1772 Traceback (most recent call last):
1773 ...
1774 KeyError
1775
1776 We wrap the original exception to give the calling application
1777 access to the test and example information.
1778
1779 If the output doesn't match, then a DocTestFailure is raised:
1780
Edward Lopera1ef6112004-08-09 16:14:41 +00001781 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001782 ... >>> x = 1
1783 ... >>> x
1784 ... 2
1785 ... ''', {}, 'foo', 'foo.py', 0)
1786
1787 >>> try:
1788 ... runner.run(test)
1789 ... except DocTestFailure, failure:
1790 ... pass
1791
1792 DocTestFailure objects provide access to the test:
1793
1794 >>> failure.test is test
1795 True
1796
1797 As well as to the example:
1798
1799 >>> failure.example.want
1800 '2\n'
1801
1802 and the actual output:
1803
1804 >>> failure.got
1805 '1\n'
1806
1807 If a failure or error occurs, the globals are left intact:
1808
1809 >>> del test.globs['__builtins__']
1810 >>> test.globs
1811 {'x': 1}
1812
Edward Lopera1ef6112004-08-09 16:14:41 +00001813 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001814 ... >>> x = 2
1815 ... >>> raise KeyError
1816 ... ''', {}, 'foo', 'foo.py', 0)
1817
1818 >>> runner.run(test)
1819 Traceback (most recent call last):
1820 ...
1821 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001822
Tim Peters19397e52004-08-06 22:02:59 +00001823 >>> del test.globs['__builtins__']
1824 >>> test.globs
1825 {'x': 2}
1826
1827 But the globals are cleared if there is no error:
1828
Edward Lopera1ef6112004-08-09 16:14:41 +00001829 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001830 ... >>> x = 2
1831 ... ''', {}, 'foo', 'foo.py', 0)
1832
1833 >>> runner.run(test)
1834 (0, 1)
1835
1836 >>> test.globs
1837 {}
1838
1839 """
1840
1841 def run(self, test, compileflags=None, out=None, clear_globs=True):
1842 r = DocTestRunner.run(self, test, compileflags, out, False)
1843 if clear_globs:
1844 test.globs.clear()
1845 return r
1846
1847 def report_unexpected_exception(self, out, test, example, exc_info):
1848 raise UnexpectedException(test, example, exc_info)
1849
1850 def report_failure(self, out, test, example, got):
1851 raise DocTestFailure(test, example, got)
1852
Tim Peters8485b562004-08-04 18:46:34 +00001853######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001854## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001855######################################################################
1856# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001857
Tim Peters82076ef2004-09-13 00:52:51 +00001858# For backward compatibility, a global instance of a DocTestRunner
1859# class, updated by testmod.
1860master = None
1861
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001862def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001863 report=True, optionflags=0, extraglobs=None,
Tim Peters958cc892004-09-13 14:53:28 +00001864 raise_on_error=False, exclude_empty=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001865 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters958cc892004-09-13 14:53:28 +00001866 report=True, optionflags=0, extraglobs=None, raise_on_error=False,
1867 exclude_empty=False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001868
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001869 Test examples in docstrings in functions and classes reachable
1870 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001871 with m.__doc__. Unless isprivate is specified, private names
1872 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001873
1874 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001875 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001876 function and class docstrings are tested even if the name is private;
1877 strings are tested directly, as if they were docstrings.
1878
1879 Return (#failures, #tests).
1880
1881 See doctest.__doc__ for an overview.
1882
1883 Optional keyword arg "name" gives the name of the module; by default
1884 use m.__name__.
1885
1886 Optional keyword arg "globs" gives a dict to be used as the globals
1887 when executing examples; by default, use m.__dict__. A copy of this
1888 dict is actually used for each docstring, so that each docstring's
1889 examples start with a clean slate.
1890
Tim Peters8485b562004-08-04 18:46:34 +00001891 Optional keyword arg "extraglobs" gives a dictionary that should be
1892 merged into the globals that are used to execute examples. By
1893 default, no extra globals are used. This is new in 2.4.
1894
Tim Peters8a7d2d52001-01-16 07:10:57 +00001895 Optional keyword arg "verbose" prints lots of stuff if true, prints
1896 only failures if false; by default, it's true iff "-v" is in sys.argv.
1897
Tim Peters8a7d2d52001-01-16 07:10:57 +00001898 Optional keyword arg "report" prints a summary at the end when true,
1899 else prints nothing at the end. In verbose mode, the summary is
1900 detailed, else very brief (in fact, empty if all tests passed).
1901
Tim Peters6ebe61f2003-06-27 20:48:05 +00001902 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001903 and defaults to 0. This is new in 2.3. Possible values (see the
1904 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001905
1906 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001907 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001908 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001909 ELLIPSIS
Edward Loper052d0cd2004-09-19 17:19:33 +00001910 IGNORE_EXCEPTION_DETAIL
Edward Loper71f55af2004-08-26 01:41:51 +00001911 REPORT_UDIFF
1912 REPORT_CDIFF
1913 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001914 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001915
1916 Optional keyword arg "raise_on_error" raises an exception on the
1917 first unexpected exception or failure. This allows failures to be
1918 post-mortem debugged.
1919
Tim Petersf727c6c2004-08-08 01:48:59 +00001920 Deprecated in Python 2.4:
1921 Optional keyword arg "isprivate" specifies a function used to
1922 determine whether a name is private. The default function is
1923 treat all functions as public. Optionally, "isprivate" can be
1924 set to doctest.is_private to skip over functions marked as private
1925 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001926
Tim Peters8a7d2d52001-01-16 07:10:57 +00001927 Advanced tomfoolery: testmod runs methods of a local instance of
1928 class doctest.Tester, then merges the results into (or creates)
1929 global Tester instance doctest.master. Methods of doctest.master
1930 can be called directly too, if you want to do something unusual.
1931 Passing report=0 to testmod is especially useful then, to delay
1932 displaying a summary. Invoke doctest.master.summarize(verbose)
1933 when you're done fiddling.
1934 """
Tim Peters82076ef2004-09-13 00:52:51 +00001935 global master
1936
Tim Petersf727c6c2004-08-08 01:48:59 +00001937 if isprivate is not None:
1938 warnings.warn("the isprivate argument is deprecated; "
1939 "examine DocTestFinder.find() lists instead",
1940 DeprecationWarning)
1941
Tim Peters8485b562004-08-04 18:46:34 +00001942 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001943 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001944 # DWA - m will still be None if this wasn't invoked from the command
1945 # line, in which case the following TypeError is about as good an error
1946 # as we should expect
1947 m = sys.modules.get('__main__')
1948
Tim Peters8485b562004-08-04 18:46:34 +00001949 # Check that we were actually given a module.
1950 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001951 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001952
1953 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001954 if name is None:
1955 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001956
1957 # Find, parse, and run all tests in the given module.
Tim Peters958cc892004-09-13 14:53:28 +00001958 finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty)
Tim Peters19397e52004-08-06 22:02:59 +00001959
1960 if raise_on_error:
1961 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1962 else:
1963 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1964
Tim Peters8485b562004-08-04 18:46:34 +00001965 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1966 runner.run(test)
1967
Tim Peters8a7d2d52001-01-16 07:10:57 +00001968 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001969 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001970
Tim Peters82076ef2004-09-13 00:52:51 +00001971 if master is None:
1972 master = runner
1973 else:
1974 master.merge(runner)
1975
Tim Peters8485b562004-08-04 18:46:34 +00001976 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001977
Edward Loper052d0cd2004-09-19 17:19:33 +00001978def testfile(filename, module_relative=True, name=None, package=None,
1979 globs=None, verbose=None, report=True, optionflags=0,
1980 extraglobs=None, raise_on_error=False):
1981 """
1982 Test examples in the given file. Return (#failures, #tests).
1983
1984 Optional keyword arg "module_relative" specifies how filenames
1985 should be interpreted:
1986
1987 - If "module_relative" is True (the default), then "filename"
1988 specifies a module-relative path. By default, this path is
1989 relative to the calling module's directory; but if the
1990 "package" argument is specified, then it is relative to that
1991 package. To ensure os-independence, "filename" should use
1992 "/" characters to separate path segments, and should not
1993 be an absolute path (i.e., it may not begin with "/").
1994
1995 - If "module_relative" is False, then "filename" specifies an
1996 os-specific path. The path may be absolute or relative (to
1997 the current working directory).
1998
Edward Lopera2fc7ec2004-09-21 03:24:24 +00001999 Optional keyword arg "name" gives the name of the test; by default
2000 use the file's basename.
Edward Loper052d0cd2004-09-19 17:19:33 +00002001
2002 Optional keyword argument "package" is a Python package or the
2003 name of a Python package whose directory should be used as the
2004 base directory for a module relative filename. If no package is
2005 specified, then the calling module's directory is used as the base
2006 directory for module relative filenames. It is an error to
2007 specify "package" if "module_relative" is False.
2008
2009 Optional keyword arg "globs" gives a dict to be used as the globals
2010 when executing examples; by default, use {}. A copy of this dict
2011 is actually used for each docstring, so that each docstring's
2012 examples start with a clean slate.
2013
2014 Optional keyword arg "extraglobs" gives a dictionary that should be
2015 merged into the globals that are used to execute examples. By
2016 default, no extra globals are used.
2017
2018 Optional keyword arg "verbose" prints lots of stuff if true, prints
2019 only failures if false; by default, it's true iff "-v" is in sys.argv.
2020
2021 Optional keyword arg "report" prints a summary at the end when true,
2022 else prints nothing at the end. In verbose mode, the summary is
2023 detailed, else very brief (in fact, empty if all tests passed).
2024
2025 Optional keyword arg "optionflags" or's together module constants,
2026 and defaults to 0. Possible values (see the docs for details):
2027
2028 DONT_ACCEPT_TRUE_FOR_1
2029 DONT_ACCEPT_BLANKLINE
2030 NORMALIZE_WHITESPACE
2031 ELLIPSIS
2032 IGNORE_EXCEPTION_DETAIL
2033 REPORT_UDIFF
2034 REPORT_CDIFF
2035 REPORT_NDIFF
2036 REPORT_ONLY_FIRST_FAILURE
2037
2038 Optional keyword arg "raise_on_error" raises an exception on the
2039 first unexpected exception or failure. This allows failures to be
2040 post-mortem debugged.
2041
2042 Advanced tomfoolery: testmod runs methods of a local instance of
2043 class doctest.Tester, then merges the results into (or creates)
2044 global Tester instance doctest.master. Methods of doctest.master
2045 can be called directly too, if you want to do something unusual.
2046 Passing report=0 to testmod is especially useful then, to delay
2047 displaying a summary. Invoke doctest.master.summarize(verbose)
2048 when you're done fiddling.
2049 """
2050 global master
2051
2052 if package and not module_relative:
2053 raise ValueError("Package may only be specified for module-"
2054 "relative paths.")
Tim Petersbab3e992004-09-20 19:52:34 +00002055
Edward Loper052d0cd2004-09-19 17:19:33 +00002056 # Relativize the path
2057 if module_relative:
2058 package = _normalize_module(package)
2059 filename = _module_relative_path(package, filename)
2060
2061 # If no name was given, then use the file's name.
2062 if name is None:
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002063 name = os.path.basename(filename)
Edward Loper052d0cd2004-09-19 17:19:33 +00002064
2065 # Assemble the globals.
2066 if globs is None:
2067 globs = {}
2068 else:
2069 globs = globs.copy()
2070 if extraglobs is not None:
2071 globs.update(extraglobs)
2072
2073 if raise_on_error:
2074 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
2075 else:
2076 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
2077
2078 # Read the file, convert it to a test, and run it.
2079 s = open(filename).read()
2080 test = DocTestParser().get_doctest(s, globs, name, filename, 0)
2081 runner.run(test)
2082
2083 if report:
2084 runner.summarize()
2085
2086 if master is None:
2087 master = runner
2088 else:
2089 master.merge(runner)
2090
2091 return runner.failures, runner.tries
2092
Tim Peters8485b562004-08-04 18:46:34 +00002093def run_docstring_examples(f, globs, verbose=False, name="NoName",
2094 compileflags=None, optionflags=0):
2095 """
2096 Test examples in the given object's docstring (`f`), using `globs`
2097 as globals. Optional argument `name` is used in failure messages.
2098 If the optional argument `verbose` is true, then generate output
2099 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00002100
Tim Peters8485b562004-08-04 18:46:34 +00002101 `compileflags` gives the set of flags that should be used by the
2102 Python compiler when running the examples. If not specified, then
2103 it will default to the set of future-import flags that apply to
2104 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00002105
Tim Peters8485b562004-08-04 18:46:34 +00002106 Optional keyword arg `optionflags` specifies options for the
2107 testing and output. See the documentation for `testmod` for more
2108 information.
2109 """
2110 # Find, parse, and run all tests in the given module.
2111 finder = DocTestFinder(verbose=verbose, recurse=False)
2112 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
2113 for test in finder.find(f, name, globs=globs):
2114 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00002115
Tim Peters8485b562004-08-04 18:46:34 +00002116######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002117## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00002118######################################################################
2119# This is provided only for backwards compatibility. It's not
2120# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00002121
Tim Peters8485b562004-08-04 18:46:34 +00002122class Tester:
2123 def __init__(self, mod=None, globs=None, verbose=None,
2124 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00002125
2126 warnings.warn("class Tester is deprecated; "
2127 "use class doctest.DocTestRunner instead",
2128 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00002129 if mod is None and globs is None:
2130 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters4be7a922004-09-12 22:39:46 +00002131 if mod is not None and not inspect.ismodule(mod):
Tim Peters8485b562004-08-04 18:46:34 +00002132 raise TypeError("Tester.__init__: mod must be a module; %r" %
2133 (mod,))
2134 if globs is None:
2135 globs = mod.__dict__
2136 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00002137
Tim Peters8485b562004-08-04 18:46:34 +00002138 self.verbose = verbose
2139 self.isprivate = isprivate
2140 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00002141 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00002142 self.testrunner = DocTestRunner(verbose=verbose,
2143 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00002144
Tim Peters8485b562004-08-04 18:46:34 +00002145 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00002146 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00002147 if self.verbose:
2148 print "Running string", name
2149 (f,t) = self.testrunner.run(test)
2150 if self.verbose:
2151 print f, "of", t, "examples failed in string", name
2152 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002153
Tim Petersf3f57472004-08-08 06:11:48 +00002154 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00002155 f = t = 0
2156 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00002157 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00002158 for test in tests:
2159 (f2, t2) = self.testrunner.run(test)
2160 (f,t) = (f+f2, t+t2)
2161 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002162
Tim Peters8485b562004-08-04 18:46:34 +00002163 def rundict(self, d, name, module=None):
2164 import new
2165 m = new.module(name)
2166 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00002167 if module is None:
2168 module = False
2169 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00002170
Tim Peters8485b562004-08-04 18:46:34 +00002171 def run__test__(self, d, name):
2172 import new
2173 m = new.module(name)
2174 m.__test__ = d
Tim Peters9661f9a2004-09-12 22:45:17 +00002175 return self.rundoc(m, name)
Tim Petersdb3756d2003-06-29 05:30:48 +00002176
Tim Peters8485b562004-08-04 18:46:34 +00002177 def summarize(self, verbose=None):
2178 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00002179
Tim Peters8485b562004-08-04 18:46:34 +00002180 def merge(self, other):
Tim Peters82076ef2004-09-13 00:52:51 +00002181 self.testrunner.merge(other.testrunner)
Tim Petersdb3756d2003-06-29 05:30:48 +00002182
Tim Peters8485b562004-08-04 18:46:34 +00002183######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002184## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002185######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002186
Jim Fultonf54bad42004-08-28 14:57:56 +00002187_unittest_reportflags = 0
Tim Peters38330fe2004-08-30 16:19:24 +00002188
Jim Fultonf54bad42004-08-28 14:57:56 +00002189def set_unittest_reportflags(flags):
Tim Peters38330fe2004-08-30 16:19:24 +00002190 """Sets the unittest option flags.
Jim Fultonf54bad42004-08-28 14:57:56 +00002191
2192 The old flag is returned so that a runner could restore the old
2193 value if it wished to:
2194
2195 >>> old = _unittest_reportflags
2196 >>> set_unittest_reportflags(REPORT_NDIFF |
2197 ... REPORT_ONLY_FIRST_FAILURE) == old
2198 True
2199
2200 >>> import doctest
2201 >>> doctest._unittest_reportflags == (REPORT_NDIFF |
2202 ... REPORT_ONLY_FIRST_FAILURE)
2203 True
Tim Petersdf7a2082004-08-29 00:38:17 +00002204
Jim Fultonf54bad42004-08-28 14:57:56 +00002205 Only reporting flags can be set:
2206
2207 >>> set_unittest_reportflags(ELLIPSIS)
2208 Traceback (most recent call last):
2209 ...
Tim Peters38330fe2004-08-30 16:19:24 +00002210 ValueError: ('Only reporting flags allowed', 8)
Jim Fultonf54bad42004-08-28 14:57:56 +00002211
2212 >>> set_unittest_reportflags(old) == (REPORT_NDIFF |
2213 ... REPORT_ONLY_FIRST_FAILURE)
2214 True
Jim Fultonf54bad42004-08-28 14:57:56 +00002215 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002216 global _unittest_reportflags
Tim Peters38330fe2004-08-30 16:19:24 +00002217
2218 if (flags & REPORTING_FLAGS) != flags:
2219 raise ValueError("Only reporting flags allowed", flags)
Jim Fultonf54bad42004-08-28 14:57:56 +00002220 old = _unittest_reportflags
2221 _unittest_reportflags = flags
2222 return old
Tim Petersdf7a2082004-08-29 00:38:17 +00002223
Jim Fultonf54bad42004-08-28 14:57:56 +00002224
Tim Peters19397e52004-08-06 22:02:59 +00002225class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002226
Edward Loper34fcb142004-08-09 02:45:41 +00002227 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2228 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002229
Jim Fultona643b652004-07-14 19:06:50 +00002230 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002231 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002232 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002233 self._dt_test = test
2234 self._dt_setUp = setUp
2235 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002236
Jim Fultona643b652004-07-14 19:06:50 +00002237 def setUp(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002238 test = self._dt_test
Tim Petersdf7a2082004-08-29 00:38:17 +00002239
Tim Peters19397e52004-08-06 22:02:59 +00002240 if self._dt_setUp is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002241 self._dt_setUp(test)
Jim Fultona643b652004-07-14 19:06:50 +00002242
2243 def tearDown(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002244 test = self._dt_test
2245
Tim Peters19397e52004-08-06 22:02:59 +00002246 if self._dt_tearDown is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002247 self._dt_tearDown(test)
2248
2249 test.globs.clear()
Jim Fultona643b652004-07-14 19:06:50 +00002250
2251 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002252 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002253 old = sys.stdout
2254 new = StringIO()
Jim Fultonf54bad42004-08-28 14:57:56 +00002255 optionflags = self._dt_optionflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002256
Tim Peters38330fe2004-08-30 16:19:24 +00002257 if not (optionflags & REPORTING_FLAGS):
Jim Fultonf54bad42004-08-28 14:57:56 +00002258 # The option flags don't include any reporting flags,
2259 # so add the default reporting flags
2260 optionflags |= _unittest_reportflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002261
Jim Fultonf54bad42004-08-28 14:57:56 +00002262 runner = DocTestRunner(optionflags=optionflags,
Edward Loper34fcb142004-08-09 02:45:41 +00002263 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002264
Jim Fultona643b652004-07-14 19:06:50 +00002265 try:
Tim Peters19397e52004-08-06 22:02:59 +00002266 runner.DIVIDER = "-"*70
Jim Fultonf54bad42004-08-28 14:57:56 +00002267 failures, tries = runner.run(
2268 test, out=new.write, clear_globs=False)
Jim Fultona643b652004-07-14 19:06:50 +00002269 finally:
2270 sys.stdout = old
2271
2272 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002273 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002274
Tim Peters19397e52004-08-06 22:02:59 +00002275 def format_failure(self, err):
2276 test = self._dt_test
2277 if test.lineno is None:
2278 lineno = 'unknown line number'
2279 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002280 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002281 lname = '.'.join(test.name.split('.')[-1:])
2282 return ('Failed doctest test for %s\n'
2283 ' File "%s", line %s, in %s\n\n%s'
2284 % (test.name, test.filename, lineno, lname, err)
2285 )
2286
2287 def debug(self):
2288 r"""Run the test case without results and without catching exceptions
2289
2290 The unit test framework includes a debug method on test cases
2291 and test suites to support post-mortem debugging. The test code
2292 is run in such a way that errors are not caught. This way a
2293 caller can catch the errors and initiate post-mortem debugging.
2294
2295 The DocTestCase provides a debug method that raises
2296 UnexpectedException errors if there is an unexepcted
2297 exception:
2298
Edward Lopera1ef6112004-08-09 16:14:41 +00002299 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002300 ... {}, 'foo', 'foo.py', 0)
2301 >>> case = DocTestCase(test)
2302 >>> try:
2303 ... case.debug()
2304 ... except UnexpectedException, failure:
2305 ... pass
2306
2307 The UnexpectedException contains the test, the example, and
2308 the original exception:
2309
2310 >>> failure.test is test
2311 True
2312
2313 >>> failure.example.want
2314 '42\n'
2315
2316 >>> exc_info = failure.exc_info
2317 >>> raise exc_info[0], exc_info[1], exc_info[2]
2318 Traceback (most recent call last):
2319 ...
2320 KeyError
2321
2322 If the output doesn't match, then a DocTestFailure is raised:
2323
Edward Lopera1ef6112004-08-09 16:14:41 +00002324 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002325 ... >>> x = 1
2326 ... >>> x
2327 ... 2
2328 ... ''', {}, 'foo', 'foo.py', 0)
2329 >>> case = DocTestCase(test)
2330
2331 >>> try:
2332 ... case.debug()
2333 ... except DocTestFailure, failure:
2334 ... pass
2335
2336 DocTestFailure objects provide access to the test:
2337
2338 >>> failure.test is test
2339 True
2340
2341 As well as to the example:
2342
2343 >>> failure.example.want
2344 '2\n'
2345
2346 and the actual output:
2347
2348 >>> failure.got
2349 '1\n'
2350
2351 """
2352
Jim Fultonf54bad42004-08-28 14:57:56 +00002353 self.setUp()
Edward Loper34fcb142004-08-09 02:45:41 +00002354 runner = DebugRunner(optionflags=self._dt_optionflags,
2355 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002356 runner.run(self._dt_test)
Jim Fultonf54bad42004-08-28 14:57:56 +00002357 self.tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002358
2359 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002360 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002361
2362 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002363 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002364 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2365
2366 __str__ = __repr__
2367
2368 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002369 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002370
Jim Fultonf54bad42004-08-28 14:57:56 +00002371def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2372 **options):
Tim Peters8485b562004-08-04 18:46:34 +00002373 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002374 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002375
Tim Peters19397e52004-08-06 22:02:59 +00002376 This converts each documentation string in a module that
2377 contains doctest tests to a unittest test case. If any of the
2378 tests in a doc string fail, then the test case fails. An exception
2379 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002380 (sometimes approximate) line number.
2381
Tim Peters19397e52004-08-06 22:02:59 +00002382 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002383 can be either a module or a module name.
2384
2385 If no argument is given, the calling module is used.
Jim Fultonf54bad42004-08-28 14:57:56 +00002386
2387 A number of options may be provided as keyword arguments:
2388
Jim Fultonf54bad42004-08-28 14:57:56 +00002389 setUp
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002390 A set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002391 tests in each file. The setUp function will be passed a DocTest
2392 object. The setUp function can access the test globals as the
2393 globs attribute of the test passed.
2394
2395 tearDown
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002396 A tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002397 tests in each file. The tearDown function will be passed a DocTest
2398 object. The tearDown function can access the test globals as the
2399 globs attribute of the test passed.
2400
2401 globs
2402 A dictionary containing initial global variables for the tests.
2403
2404 optionflags
2405 A set of doctest option flags expressed as an integer.
Jim Fultona643b652004-07-14 19:06:50 +00002406 """
Jim Fultona643b652004-07-14 19:06:50 +00002407
Tim Peters8485b562004-08-04 18:46:34 +00002408 if test_finder is None:
2409 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002410
Tim Peters19397e52004-08-06 22:02:59 +00002411 module = _normalize_module(module)
2412 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2413 if globs is None:
2414 globs = module.__dict__
Jim Fultonf54bad42004-08-28 14:57:56 +00002415 if not tests:
2416 # Why do we want to do this? Because it reveals a bug that might
2417 # otherwise be hidden.
Tim Peters19397e52004-08-06 22:02:59 +00002418 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002419
2420 tests.sort()
2421 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002422 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002423 if len(test.examples) == 0:
2424 continue
Tim Peters8485b562004-08-04 18:46:34 +00002425 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002426 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002427 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002428 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002429 test.filename = filename
Jim Fultonf54bad42004-08-28 14:57:56 +00002430 suite.addTest(DocTestCase(test, **options))
Tim Peters19397e52004-08-06 22:02:59 +00002431
2432 return suite
2433
2434class DocFileCase(DocTestCase):
2435
2436 def id(self):
2437 return '_'.join(self._dt_test.name.split('.'))
2438
2439 def __repr__(self):
2440 return self._dt_test.filename
2441 __str__ = __repr__
2442
2443 def format_failure(self, err):
2444 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2445 % (self._dt_test.name, self._dt_test.filename, err)
2446 )
2447
Edward Loper052d0cd2004-09-19 17:19:33 +00002448def DocFileTest(path, module_relative=True, package=None,
2449 globs=None, **options):
Tim Peters19397e52004-08-06 22:02:59 +00002450 if globs is None:
2451 globs = {}
2452
Edward Loper052d0cd2004-09-19 17:19:33 +00002453 if package and not module_relative:
2454 raise ValueError("Package may only be specified for module-"
2455 "relative paths.")
Tim Petersbab3e992004-09-20 19:52:34 +00002456
Edward Loper052d0cd2004-09-19 17:19:33 +00002457 # Relativize the path.
2458 if module_relative:
2459 package = _normalize_module(package)
2460 path = _module_relative_path(package, path)
Tim Peters19397e52004-08-06 22:02:59 +00002461
Edward Loper052d0cd2004-09-19 17:19:33 +00002462 # Find the file and read it.
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002463 name = os.path.basename(path)
Edward Loper052d0cd2004-09-19 17:19:33 +00002464 doc = open(path).read()
2465
2466 # Convert it to a test, and wrap it in a DocFileCase.
2467 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Jim Fultonf54bad42004-08-28 14:57:56 +00002468 return DocFileCase(test, **options)
Tim Peters19397e52004-08-06 22:02:59 +00002469
2470def DocFileSuite(*paths, **kw):
Edward Loper052d0cd2004-09-19 17:19:33 +00002471 """A unittest suite for one or more doctest files.
Tim Petersbab3e992004-09-20 19:52:34 +00002472
Edward Loper052d0cd2004-09-19 17:19:33 +00002473 The path to each doctest file is given as a string; the
2474 interpretation of that string depends on the keyword argument
2475 "module_relative".
Tim Peters19397e52004-08-06 22:02:59 +00002476
2477 A number of options may be provided as keyword arguments:
2478
Edward Loper052d0cd2004-09-19 17:19:33 +00002479 module_relative
2480 If "module_relative" is True, then the given file paths are
2481 interpreted as os-independent module-relative paths. By
2482 default, these paths are relative to the calling module's
2483 directory; but if the "package" argument is specified, then
2484 they are relative to that package. To ensure os-independence,
2485 "filename" should use "/" characters to separate path
2486 segments, and may not be an absolute path (i.e., it may not
2487 begin with "/").
Tim Petersbab3e992004-09-20 19:52:34 +00002488
Edward Loper052d0cd2004-09-19 17:19:33 +00002489 If "module_relative" is False, then the given file paths are
2490 interpreted as os-specific paths. These paths may be absolute
2491 or relative (to the current working directory).
2492
Tim Peters19397e52004-08-06 22:02:59 +00002493 package
Edward Loper052d0cd2004-09-19 17:19:33 +00002494 A Python package or the name of a Python package whose directory
2495 should be used as the base directory for module relative paths.
2496 If "package" is not specified, then the calling module's
2497 directory is used as the base directory for module relative
2498 filenames. It is an error to specify "package" if
2499 "module_relative" is False.
Tim Peters19397e52004-08-06 22:02:59 +00002500
2501 setUp
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002502 A set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002503 tests in each file. The setUp function will be passed a DocTest
2504 object. The setUp function can access the test globals as the
2505 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002506
2507 tearDown
Edward Lopera2fc7ec2004-09-21 03:24:24 +00002508 A tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002509 tests in each file. The tearDown function will be passed a DocTest
2510 object. The tearDown function can access the test globals as the
2511 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002512
2513 globs
2514 A dictionary containing initial global variables for the tests.
Jim Fultonf54bad42004-08-28 14:57:56 +00002515
2516 optionflags
2517 A set of doctest option flags expressed as an integer.
Tim Peters19397e52004-08-06 22:02:59 +00002518 """
2519 suite = unittest.TestSuite()
2520
2521 # We do this here so that _normalize_module is called at the right
2522 # level. If it were called in DocFileTest, then this function
2523 # would be the caller and we might guess the package incorrectly.
Edward Loper052d0cd2004-09-19 17:19:33 +00002524 if kw.get('module_relative', True):
2525 kw['package'] = _normalize_module(kw.get('package'))
Tim Peters19397e52004-08-06 22:02:59 +00002526
2527 for path in paths:
2528 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002529
Tim Petersdb3756d2003-06-29 05:30:48 +00002530 return suite
2531
Tim Peters8485b562004-08-04 18:46:34 +00002532######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002533## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002534######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002535
Tim Peters19397e52004-08-06 22:02:59 +00002536def script_from_examples(s):
2537 r"""Extract script from text with examples.
2538
2539 Converts text with examples to a Python script. Example input is
2540 converted to regular code. Example output and all other words
2541 are converted to comments:
2542
2543 >>> text = '''
2544 ... Here are examples of simple math.
2545 ...
2546 ... Python has super accurate integer addition
2547 ...
2548 ... >>> 2 + 2
2549 ... 5
2550 ...
2551 ... And very friendly error messages:
2552 ...
2553 ... >>> 1/0
2554 ... To Infinity
2555 ... And
2556 ... Beyond
2557 ...
2558 ... You can use logic if you want:
2559 ...
2560 ... >>> if 0:
2561 ... ... blah
2562 ... ... blah
2563 ... ...
2564 ...
2565 ... Ho hum
2566 ... '''
2567
2568 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002569 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002570 #
Edward Lopera5db6002004-08-12 02:41:30 +00002571 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002572 #
2573 2 + 2
2574 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002575 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002576 #
Edward Lopera5db6002004-08-12 02:41:30 +00002577 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002578 #
2579 1/0
2580 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002581 ## To Infinity
2582 ## And
2583 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002584 #
Edward Lopera5db6002004-08-12 02:41:30 +00002585 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002586 #
2587 if 0:
2588 blah
2589 blah
Tim Peters19397e52004-08-06 22:02:59 +00002590 #
Edward Lopera5db6002004-08-12 02:41:30 +00002591 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002592 """
Edward Loper00f8da72004-08-26 18:05:07 +00002593 output = []
2594 for piece in DocTestParser().parse(s):
2595 if isinstance(piece, Example):
2596 # Add the example's source code (strip trailing NL)
2597 output.append(piece.source[:-1])
2598 # Add the expected output:
2599 want = piece.want
2600 if want:
2601 output.append('# Expected:')
2602 output += ['## '+l for l in want.split('\n')[:-1]]
2603 else:
2604 # Add non-example text.
2605 output += [_comment_line(l)
2606 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002607
Edward Loper00f8da72004-08-26 18:05:07 +00002608 # Trim junk on both ends.
2609 while output and output[-1] == '#':
2610 output.pop()
2611 while output and output[0] == '#':
2612 output.pop(0)
2613 # Combine the output, and return it.
2614 return '\n'.join(output)
Tim Petersdb3756d2003-06-29 05:30:48 +00002615
2616def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002617 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002618
2619 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002620 test to be debugged and the name (within the module) of the object
2621 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002622 """
Tim Peters8485b562004-08-04 18:46:34 +00002623 module = _normalize_module(module)
2624 tests = DocTestFinder().find(module)
2625 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002626 if not test:
2627 raise ValueError(name, "not found in tests")
2628 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002629 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002630 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002631
Jim Fultona643b652004-07-14 19:06:50 +00002632def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002633 """Debug a single doctest docstring, in argument `src`'"""
2634 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002635 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002636
Jim Fultona643b652004-07-14 19:06:50 +00002637def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002638 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002639 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002640
Tim Petersb6a04d62004-08-23 21:37:56 +00002641 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2642 # docs say, a file so created cannot be opened by name a second time
2643 # on modern Windows boxes, and execfile() needs to open it.
2644 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002645 f = open(srcfilename, 'w')
2646 f.write(src)
2647 f.close()
2648
Tim Petersb6a04d62004-08-23 21:37:56 +00002649 try:
2650 if globs:
2651 globs = globs.copy()
2652 else:
2653 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002654
Tim Petersb6a04d62004-08-23 21:37:56 +00002655 if pm:
2656 try:
2657 execfile(srcfilename, globs, globs)
2658 except:
2659 print sys.exc_info()[1]
2660 pdb.post_mortem(sys.exc_info()[2])
2661 else:
2662 # Note that %r is vital here. '%s' instead can, e.g., cause
2663 # backslashes to get treated as metacharacters on Windows.
2664 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2665
2666 finally:
2667 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002668
Jim Fultona643b652004-07-14 19:06:50 +00002669def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002670 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002671
2672 Provide the module (or dotted name of the module) containing the
2673 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002674 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002675 """
Tim Peters8485b562004-08-04 18:46:34 +00002676 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002677 testsrc = testsource(module, name)
2678 debug_script(testsrc, pm, module.__dict__)
2679
Tim Peters8485b562004-08-04 18:46:34 +00002680######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002681## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002682######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002683class _TestClass:
2684 """
2685 A pointless class, for sanity-checking of docstring testing.
2686
2687 Methods:
2688 square()
2689 get()
2690
2691 >>> _TestClass(13).get() + _TestClass(-12).get()
2692 1
2693 >>> hex(_TestClass(13).square().get())
2694 '0xa9'
2695 """
2696
2697 def __init__(self, val):
2698 """val -> _TestClass object with associated value val.
2699
2700 >>> t = _TestClass(123)
2701 >>> print t.get()
2702 123
2703 """
2704
2705 self.val = val
2706
2707 def square(self):
2708 """square() -> square TestClass's associated value
2709
2710 >>> _TestClass(13).square().get()
2711 169
2712 """
2713
2714 self.val = self.val ** 2
2715 return self
2716
2717 def get(self):
2718 """get() -> return TestClass's associated value.
2719
2720 >>> x = _TestClass(-42)
2721 >>> print x.get()
2722 -42
2723 """
2724
2725 return self.val
2726
2727__test__ = {"_TestClass": _TestClass,
2728 "string": r"""
2729 Example of a string object, searched as-is.
2730 >>> x = 1; y = 2
2731 >>> x + y, x * y
2732 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002733 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002734
Tim Peters6ebe61f2003-06-27 20:48:05 +00002735 "bool-int equivalence": r"""
2736 In 2.2, boolean expressions displayed
2737 0 or 1. By default, we still accept
2738 them. This can be disabled by passing
2739 DONT_ACCEPT_TRUE_FOR_1 to the new
2740 optionflags argument.
2741 >>> 4 == 4
2742 1
2743 >>> 4 == 4
2744 True
2745 >>> 4 > 4
2746 0
2747 >>> 4 > 4
2748 False
2749 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002750
Tim Peters8485b562004-08-04 18:46:34 +00002751 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002752 Blank lines can be marked with <BLANKLINE>:
2753 >>> print 'foo\n\nbar\n'
2754 foo
2755 <BLANKLINE>
2756 bar
2757 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002758 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002759
2760 "ellipsis": r"""
2761 If the ellipsis flag is used, then '...' can be used to
2762 elide substrings in the desired output:
2763 >>> print range(1000) #doctest: +ELLIPSIS
2764 [0, 1, 2, ..., 999]
2765 """,
2766
2767 "whitespace normalization": r"""
2768 If the whitespace normalization flag is used, then
2769 differences in whitespace are ignored.
2770 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2771 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2772 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2773 27, 28, 29]
2774 """,
2775 }
Tim Peters8485b562004-08-04 18:46:34 +00002776
Tim Peters8a7d2d52001-01-16 07:10:57 +00002777def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002778 r = unittest.TextTestRunner()
2779 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002780
2781if __name__ == "__main__":
2782 _test()