blob: 5d371d29ccd9de23e60017621ad4d88d7ab91349 [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',
203 'run_docstring_examples',
Edward Loperb7503ff2004-08-19 19:19:03 +0000204 # 7. Tester
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000205 'Tester',
Edward Loperb7503ff2004-08-19 19:19:03 +0000206 # 8. Unittest Support
Tim Peters19397e52004-08-06 22:02:59 +0000207 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000208 'DocTestSuite',
Edward Loperb7503ff2004-08-19 19:19:03 +0000209 'DocFileCase',
210 'DocFileTest',
211 'DocFileSuite',
212 # 9. Debugging Support
213 'script_from_examples',
Tim Petersdb3756d2003-06-29 05:30:48 +0000214 'testsource',
Edward Loperb7503ff2004-08-19 19:19:03 +0000215 'debug_src',
216 'debug_script',
Tim Petersdb3756d2003-06-29 05:30:48 +0000217 'debug',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000218]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000219
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000220import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000221
Tim Peters19397e52004-08-06 22:02:59 +0000222import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000223import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000224import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000225from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000226
Tim Petersdd50cb72004-08-23 22:42:55 +0000227# Don't whine about the deprecated is_private function in this
228# module's tests.
229warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
230 __name__, 0)
231
Jim Fulton356fd192004-08-09 11:34:47 +0000232real_pdb_set_trace = pdb.set_trace
233
Tim Peters19397e52004-08-06 22:02:59 +0000234# There are 4 basic classes:
235# - Example: a <source, want> pair, plus an intra-docstring line number.
236# - DocTest: a collection of examples, parsed from a docstring, plus
237# info about where the docstring came from (name, filename, lineno).
238# - DocTestFinder: extracts DocTests from a given object's docstring and
239# its contained objects' docstrings.
240# - DocTestRunner: runs DocTest cases, and accumulates statistics.
241#
242# So the basic picture is:
243#
244# list of:
245# +------+ +---------+ +-------+
246# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
247# +------+ +---------+ +-------+
248# | Example |
249# | ... |
250# | Example |
251# +---------+
252
Edward Loperac20f572004-08-12 02:02:24 +0000253# Option constants.
Tim Peters38330fe2004-08-30 16:19:24 +0000254
Edward Loperac20f572004-08-12 02:02:24 +0000255OPTIONFLAGS_BY_NAME = {}
256def register_optionflag(name):
257 flag = 1 << len(OPTIONFLAGS_BY_NAME)
258 OPTIONFLAGS_BY_NAME[name] = flag
259 return flag
260
261DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
262DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
263NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
264ELLIPSIS = register_optionflag('ELLIPSIS')
Tim Peters1fbf9c52004-09-04 17:21:02 +0000265IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
Tim Peters38330fe2004-08-30 16:19:24 +0000266
267COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
268 DONT_ACCEPT_BLANKLINE |
269 NORMALIZE_WHITESPACE |
Tim Peters1fbf9c52004-09-04 17:21:02 +0000270 ELLIPSIS |
271 IGNORE_EXCEPTION_DETAIL)
Tim Peters38330fe2004-08-30 16:19:24 +0000272
Edward Loper71f55af2004-08-26 01:41:51 +0000273REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
274REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
275REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
Edward Lopera89f88d2004-08-26 02:45:51 +0000276REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
Edward Loperac20f572004-08-12 02:02:24 +0000277
Tim Peters38330fe2004-08-30 16:19:24 +0000278REPORTING_FLAGS = (REPORT_UDIFF |
279 REPORT_CDIFF |
280 REPORT_NDIFF |
281 REPORT_ONLY_FIRST_FAILURE)
282
Edward Loperac20f572004-08-12 02:02:24 +0000283# Special string markers for use in `want` strings:
284BLANKLINE_MARKER = '<BLANKLINE>'
285ELLIPSIS_MARKER = '...'
286
Tim Peters8485b562004-08-04 18:46:34 +0000287######################################################################
288## Table of Contents
289######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000290# 1. Utility Functions
291# 2. Example & DocTest -- store test cases
292# 3. DocTest Parser -- extracts examples from strings
293# 4. DocTest Finder -- extracts test cases from objects
294# 5. DocTest Runner -- runs test cases
295# 6. Test Functions -- convenient wrappers for testing
296# 7. Tester Class -- for backwards compatibility
297# 8. Unittest Support
298# 9. Debugging Support
299# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000300
Tim Peters8485b562004-08-04 18:46:34 +0000301######################################################################
302## 1. Utility Functions
303######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000304
305def is_private(prefix, base):
306 """prefix, base -> true iff name prefix + "." + base is "private".
307
308 Prefix may be an empty string, and base does not contain a period.
309 Prefix is ignored (although functions you write conforming to this
310 protocol may make use of it).
311 Return true iff base begins with an (at least one) underscore, but
312 does not both begin and end with (at least) two underscores.
313
314 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000315 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000316 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000317 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000318 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000319 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000320 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000321 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000322 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000323 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000324 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000325 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000326 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000327 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000328 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000329 warnings.warn("is_private is deprecated; it wasn't useful; "
330 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000331 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000332 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
333
Tim Peters8485b562004-08-04 18:46:34 +0000334def _extract_future_flags(globs):
335 """
336 Return the compiler-flags associated with the future features that
337 have been imported into the given namespace (globs).
338 """
339 flags = 0
340 for fname in __future__.all_feature_names:
341 feature = globs.get(fname, None)
342 if feature is getattr(__future__, fname):
343 flags |= feature.compiler_flag
344 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000345
Tim Peters8485b562004-08-04 18:46:34 +0000346def _normalize_module(module, depth=2):
347 """
348 Return the module specified by `module`. In particular:
349 - If `module` is a module, then return module.
350 - If `module` is a string, then import and return the
351 module with that name.
352 - If `module` is None, then return the calling module.
353 The calling module is assumed to be the module of
354 the stack frame at the given depth in the call stack.
355 """
356 if inspect.ismodule(module):
357 return module
358 elif isinstance(module, (str, unicode)):
359 return __import__(module, globals(), locals(), ["*"])
360 elif module is None:
361 return sys.modules[sys._getframe(depth).f_globals['__name__']]
362 else:
363 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000364
Edward Loperaacf0832004-08-26 01:19:50 +0000365def _indent(s, indent=4):
Tim Peters8485b562004-08-04 18:46:34 +0000366 """
Edward Loperaacf0832004-08-26 01:19:50 +0000367 Add the given number of space characters to the beginning every
368 non-blank line in `s`, and return the result.
Tim Peters8485b562004-08-04 18:46:34 +0000369 """
Edward Loperaacf0832004-08-26 01:19:50 +0000370 # This regexp matches the start of non-blank lines:
371 return re.sub('(?m)^(?!$)', indent*' ', s)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000372
Edward Loper8e4a34b2004-08-12 02:34:27 +0000373def _exception_traceback(exc_info):
374 """
375 Return a string containing a traceback message for the given
376 exc_info tuple (as returned by sys.exc_info()).
377 """
378 # Get a traceback message.
379 excout = StringIO()
380 exc_type, exc_val, exc_tb = exc_info
381 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
382 return excout.getvalue()
383
Tim Peters8485b562004-08-04 18:46:34 +0000384# Override some StringIO methods.
385class _SpoofOut(StringIO):
386 def getvalue(self):
387 result = StringIO.getvalue(self)
388 # If anything at all was written, make sure there's a trailing
389 # newline. There's no way for the expected output to indicate
390 # that a trailing newline is missing.
391 if result and not result.endswith("\n"):
392 result += "\n"
393 # Prevent softspace from screwing up the next test case, in
394 # case they used print with a trailing comma in an example.
395 if hasattr(self, "softspace"):
396 del self.softspace
397 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000398
Tim Peters8485b562004-08-04 18:46:34 +0000399 def truncate(self, size=None):
400 StringIO.truncate(self, size)
401 if hasattr(self, "softspace"):
402 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000403
Tim Peters26b3ebb2004-08-19 08:10:08 +0000404# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000405def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000406 """
407 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000408 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000409 False
410 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000411 if ELLIPSIS_MARKER not in want:
412 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000413
Tim Peters26b3ebb2004-08-19 08:10:08 +0000414 # Find "the real" strings.
415 ws = want.split(ELLIPSIS_MARKER)
416 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000417
Tim Petersdc5de3b2004-08-19 14:06:20 +0000418 # Deal with exact matches possibly needed at one or both ends.
419 startpos, endpos = 0, len(got)
420 w = ws[0]
421 if w: # starts with exact match
422 if got.startswith(w):
423 startpos = len(w)
424 del ws[0]
425 else:
426 return False
427 w = ws[-1]
428 if w: # ends with exact match
429 if got.endswith(w):
430 endpos -= len(w)
431 del ws[-1]
432 else:
433 return False
434
435 if startpos > endpos:
436 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000437 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000438 return False
439
440 # For the rest, we only need to find the leftmost non-overlapping
441 # match for each piece. If there's no overall match that way alone,
442 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000443 for w in ws:
444 # w may be '' at times, if there are consecutive ellipses, or
445 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000446 # Search for an empty string succeeds, and doesn't change startpos.
447 startpos = got.find(w, startpos, endpos)
448 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000449 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000450 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000451
Tim Petersdc5de3b2004-08-19 14:06:20 +0000452 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000453
Edward Loper00f8da72004-08-26 18:05:07 +0000454def _comment_line(line):
455 "Return a commented form of the given line"
456 line = line.rstrip()
457 if line:
458 return '# '+line
459 else:
460 return '#'
461
Edward Loper2de91ba2004-08-27 02:07:46 +0000462class _OutputRedirectingPdb(pdb.Pdb):
463 """
464 A specialized version of the python debugger that redirects stdout
465 to a given stream when interacting with the user. Stdout is *not*
466 redirected when traced code is executed.
467 """
468 def __init__(self, out):
469 self.__out = out
470 pdb.Pdb.__init__(self)
471
472 def trace_dispatch(self, *args):
473 # Redirect stdout to the given stream.
474 save_stdout = sys.stdout
475 sys.stdout = self.__out
476 # Call Pdb's trace dispatch method.
477 pdb.Pdb.trace_dispatch(self, *args)
478 # Restore stdout.
479 sys.stdout = save_stdout
480
Tim Peters8485b562004-08-04 18:46:34 +0000481######################################################################
482## 2. Example & DocTest
483######################################################################
484## - An "example" is a <source, want> pair, where "source" is a
485## fragment of source code, and "want" is the expected output for
486## "source." The Example class also includes information about
487## where the example was extracted from.
488##
Edward Lopera1ef6112004-08-09 16:14:41 +0000489## - A "doctest" is a collection of examples, typically extracted from
490## a string (such as an object's docstring). The DocTest class also
491## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000492
Tim Peters8485b562004-08-04 18:46:34 +0000493class Example:
494 """
495 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000496 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000497
Edward Loper74bca7a2004-08-12 02:27:44 +0000498 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000499 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000500
Edward Loper74bca7a2004-08-12 02:27:44 +0000501 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000502 from stdout, or a traceback in case of exception). `want` ends
503 with a newline unless it's empty, in which case it's an empty
504 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000505
Edward Lopera6b68322004-08-26 00:05:43 +0000506 - exc_msg: The exception message generated by the example, if
507 the example is expected to generate an exception; or `None` if
508 it is not expected to generate an exception. This exception
509 message is compared against the return value of
510 `traceback.format_exception_only()`. `exc_msg` ends with a
511 newline unless it's `None`. The constructor adds a newline
512 if needed.
513
Edward Loper74bca7a2004-08-12 02:27:44 +0000514 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000515 this Example where the Example begins. This line number is
516 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000517
518 - indent: The example's indentation in the DocTest string.
519 I.e., the number of space characters that preceed the
520 example's first prompt.
521
522 - options: A dictionary mapping from option flags to True or
523 False, which is used to override default options for this
524 example. Any option flags not contained in this dictionary
525 are left at their default value (as specified by the
526 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000527 """
Edward Lopera6b68322004-08-26 00:05:43 +0000528 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
529 options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000530 # Normalize inputs.
531 if not source.endswith('\n'):
532 source += '\n'
533 if want and not want.endswith('\n'):
534 want += '\n'
Edward Lopera6b68322004-08-26 00:05:43 +0000535 if exc_msg is not None and not exc_msg.endswith('\n'):
536 exc_msg += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000537 # Store properties.
538 self.source = source
539 self.want = want
540 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000541 self.indent = indent
542 if options is None: options = {}
543 self.options = options
Edward Lopera6b68322004-08-26 00:05:43 +0000544 self.exc_msg = exc_msg
Tim Peters8a7d2d52001-01-16 07:10:57 +0000545
Tim Peters8485b562004-08-04 18:46:34 +0000546class DocTest:
547 """
548 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000549 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000550
Tim Peters8485b562004-08-04 18:46:34 +0000551 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000552
Tim Peters8485b562004-08-04 18:46:34 +0000553 - globs: The namespace (aka globals) that the examples should
554 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000555
Tim Peters8485b562004-08-04 18:46:34 +0000556 - name: A name identifying the DocTest (typically, the name of
557 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000558
Tim Peters8485b562004-08-04 18:46:34 +0000559 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000560 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000561
Tim Peters8485b562004-08-04 18:46:34 +0000562 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000563 begins, or `None` if the line number is unavailable. This
564 line number is zero-based, with respect to the beginning of
565 the file.
566
567 - docstring: The string that the examples were extracted from,
568 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000569 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000570 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000571 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000572 Create a new DocTest containing the given examples. The
573 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000574 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000575 assert not isinstance(examples, basestring), \
576 "DocTest no longer accepts str; use DocTestParser instead"
577 self.examples = examples
578 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000579 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000580 self.name = name
581 self.filename = filename
582 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000583
584 def __repr__(self):
585 if len(self.examples) == 0:
586 examples = 'no examples'
587 elif len(self.examples) == 1:
588 examples = '1 example'
589 else:
590 examples = '%d examples' % len(self.examples)
591 return ('<DocTest %s from %s:%s (%s)>' %
592 (self.name, self.filename, self.lineno, examples))
593
594
595 # This lets us sort tests by name:
596 def __cmp__(self, other):
597 if not isinstance(other, DocTest):
598 return -1
599 return cmp((self.name, self.filename, self.lineno, id(self)),
600 (other.name, other.filename, other.lineno, id(other)))
601
602######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000603## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000604######################################################################
605
Edward Lopera1ef6112004-08-09 16:14:41 +0000606class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000607 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000608 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000609 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000610 # This regular expression is used to find doctest examples in a
611 # string. It defines three groups: `source` is the source code
612 # (including leading indentation and prompts); `indent` is the
613 # indentation of the first (PS1) line of the source code; and
614 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000615 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000616 # Source consists of a PS1 line followed by zero or more PS2 lines.
617 (?P<source>
618 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
619 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
620 \n?
621 # Want consists of any non-blank lines that do not start with PS1.
622 (?P<want> (?:(?![ ]*$) # Not a blank line
623 (?![ ]*>>>) # Not a line starting with PS1
624 .*$\n? # But any other line
625 )*)
626 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000627
Edward Lopera6b68322004-08-26 00:05:43 +0000628 # A regular expression for handling `want` strings that contain
629 # expected exceptions. It divides `want` into three pieces:
630 # - the traceback header line (`hdr`)
631 # - the traceback stack (`stack`)
632 # - the exception message (`msg`), as generated by
633 # traceback.format_exception_only()
634 # `msg` may have multiple lines. We assume/require that the
635 # exception message is the first non-indented line starting with a word
636 # character following the traceback header line.
637 _EXCEPTION_RE = re.compile(r"""
638 # Grab the traceback header. Different versions of Python have
639 # said different things on the first traceback line.
640 ^(?P<hdr> Traceback\ \(
641 (?: most\ recent\ call\ last
642 | innermost\ last
643 ) \) :
644 )
645 \s* $ # toss trailing whitespace on the header.
646 (?P<stack> .*?) # don't blink: absorb stuff until...
647 ^ (?P<msg> \w+ .*) # a line *starts* with alphanum.
648 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
649
Tim Peters7ea48dd2004-08-13 01:52:59 +0000650 # A callable returning a true value iff its argument is a blank line
651 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000652 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000653
Edward Loper00f8da72004-08-26 18:05:07 +0000654 def parse(self, string, name='<string>'):
655 """
656 Divide the given string into examples and intervening text,
657 and return them as a list of alternating Examples and strings.
658 Line numbers for the Examples are 0-based. The optional
659 argument `name` is a name identifying this string, and is only
660 used for error messages.
661 """
662 string = string.expandtabs()
663 # If all lines begin with the same indentation, then strip it.
664 min_indent = self._min_indent(string)
665 if min_indent > 0:
666 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
667
668 output = []
669 charno, lineno = 0, 0
670 # Find all doctest examples in the string:
Edward Loper2de91ba2004-08-27 02:07:46 +0000671 for m in self._EXAMPLE_RE.finditer(string):
Edward Loper00f8da72004-08-26 18:05:07 +0000672 # Add the pre-example text to `output`.
673 output.append(string[charno:m.start()])
674 # Update lineno (lines before this example)
675 lineno += string.count('\n', charno, m.start())
676 # Extract info from the regexp match.
677 (source, options, want, exc_msg) = \
678 self._parse_example(m, name, lineno)
679 # Create an Example, and add it to the list.
680 if not self._IS_BLANK_OR_COMMENT(source):
681 output.append( Example(source, want, exc_msg,
682 lineno=lineno,
683 indent=min_indent+len(m.group('indent')),
684 options=options) )
685 # Update lineno (lines inside this example)
686 lineno += string.count('\n', m.start(), m.end())
687 # Update charno.
688 charno = m.end()
689 # Add any remaining post-example text to `output`.
690 output.append(string[charno:])
691 return output
692
Edward Lopera1ef6112004-08-09 16:14:41 +0000693 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000694 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000695 Extract all doctest examples from the given string, and
696 collect them into a `DocTest` object.
697
698 `globs`, `name`, `filename`, and `lineno` are attributes for
699 the new `DocTest` object. See the documentation for `DocTest`
700 for more information.
701 """
702 return DocTest(self.get_examples(string, name), globs,
703 name, filename, lineno, string)
704
705 def get_examples(self, string, name='<string>'):
706 """
707 Extract all doctest examples from the given string, and return
708 them as a list of `Example` objects. Line numbers are
709 0-based, because it's most common in doctests that nothing
710 interesting appears on the same line as opening triple-quote,
711 and so the first interesting line is called \"line 1\" then.
712
713 The optional argument `name` is a name identifying this
714 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000715 """
Edward Loper00f8da72004-08-26 18:05:07 +0000716 return [x for x in self.parse(string, name)
717 if isinstance(x, Example)]
Edward Loper7c748462004-08-09 02:06:06 +0000718
Edward Loper74bca7a2004-08-12 02:27:44 +0000719 def _parse_example(self, m, name, lineno):
720 """
721 Given a regular expression match from `_EXAMPLE_RE` (`m`),
722 return a pair `(source, want)`, where `source` is the matched
723 example's source code (with prompts and indentation stripped);
724 and `want` is the example's expected output (with indentation
725 stripped).
726
727 `name` is the string's name, and `lineno` is the line number
728 where the example starts; both are used for error messages.
729 """
Edward Loper7c748462004-08-09 02:06:06 +0000730 # Get the example's indentation level.
731 indent = len(m.group('indent'))
732
733 # Divide source into lines; check that they're properly
734 # indented; and then strip their indentation & prompts.
735 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000736 self._check_prompt_blank(source_lines, indent, name, lineno)
Tim Petersc5049152004-08-22 17:34:58 +0000737 self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000738 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000739
Tim Petersc5049152004-08-22 17:34:58 +0000740 # Divide want into lines; check that it's properly indented; and
741 # then strip the indentation. Spaces before the last newline should
742 # be preserved, so plain rstrip() isn't good enough.
Jim Fulton07a349c2004-08-22 14:10:00 +0000743 want = m.group('want')
Jim Fulton07a349c2004-08-22 14:10:00 +0000744 want_lines = want.split('\n')
Tim Petersc5049152004-08-22 17:34:58 +0000745 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
746 del want_lines[-1] # forget final newline & spaces after it
Edward Lopera1ef6112004-08-09 16:14:41 +0000747 self._check_prefix(want_lines, ' '*indent, name,
Tim Petersc5049152004-08-22 17:34:58 +0000748 lineno + len(source_lines))
Edward Loper7c748462004-08-09 02:06:06 +0000749 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000750
Edward Lopera6b68322004-08-26 00:05:43 +0000751 # If `want` contains a traceback message, then extract it.
752 m = self._EXCEPTION_RE.match(want)
753 if m:
754 exc_msg = m.group('msg')
755 else:
756 exc_msg = None
757
Edward Loper00f8da72004-08-26 18:05:07 +0000758 # Extract options from the source.
759 options = self._find_options(source, name, lineno)
760
761 return source, options, want, exc_msg
Edward Loper7c748462004-08-09 02:06:06 +0000762
Edward Loper74bca7a2004-08-12 02:27:44 +0000763 # This regular expression looks for option directives in the
764 # source code of an example. Option directives are comments
765 # starting with "doctest:". Warning: this may give false
766 # positives for string-literals that contain the string
767 # "#doctest:". Eliminating these false positives would require
768 # actually parsing the string; but we limit them by ignoring any
769 # line containing "#doctest:" that is *followed* by a quote mark.
770 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
771 re.MULTILINE)
772
773 def _find_options(self, source, name, lineno):
774 """
775 Return a dictionary containing option overrides extracted from
776 option directives in the given source string.
777
778 `name` is the string's name, and `lineno` is the line number
779 where the example starts; both are used for error messages.
780 """
781 options = {}
782 # (note: with the current regexp, this will match at most once:)
783 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
784 option_strings = m.group(1).replace(',', ' ').split()
785 for option in option_strings:
786 if (option[0] not in '+-' or
787 option[1:] not in OPTIONFLAGS_BY_NAME):
788 raise ValueError('line %r of the doctest for %s '
789 'has an invalid option: %r' %
790 (lineno+1, name, option))
791 flag = OPTIONFLAGS_BY_NAME[option[1:]]
792 options[flag] = (option[0] == '+')
793 if options and self._IS_BLANK_OR_COMMENT(source):
794 raise ValueError('line %r of the doctest for %s has an option '
795 'directive on a line with no example: %r' %
796 (lineno, name, source))
797 return options
798
Edward Lopera5db6002004-08-12 02:41:30 +0000799 # This regular expression finds the indentation of every non-blank
800 # line in a string.
Edward Loper00f8da72004-08-26 18:05:07 +0000801 _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
Edward Lopera5db6002004-08-12 02:41:30 +0000802
803 def _min_indent(self, s):
804 "Return the minimum indentation of any non-blank line in `s`"
Edward Loper00f8da72004-08-26 18:05:07 +0000805 indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
806 if len(indents) > 0:
807 return min(indents)
Tim Petersdd0e4752004-08-09 03:31:56 +0000808 else:
Edward Loper00f8da72004-08-26 18:05:07 +0000809 return 0
Edward Loper7c748462004-08-09 02:06:06 +0000810
Edward Lopera1ef6112004-08-09 16:14:41 +0000811 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000812 """
813 Given the lines of a source string (including prompts and
814 leading indentation), check to make sure that every prompt is
815 followed by a space character. If any line is not followed by
816 a space character, then raise ValueError.
817 """
Edward Loper7c748462004-08-09 02:06:06 +0000818 for i, line in enumerate(lines):
819 if len(line) >= indent+4 and line[indent+3] != ' ':
820 raise ValueError('line %r of the docstring for %s '
821 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000822 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000823 line[indent:indent+3], line))
824
Edward Lopera1ef6112004-08-09 16:14:41 +0000825 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000826 """
827 Check that every line in the given list starts with the given
828 prefix; if any line does not, then raise a ValueError.
829 """
Edward Loper7c748462004-08-09 02:06:06 +0000830 for i, line in enumerate(lines):
831 if line and not line.startswith(prefix):
832 raise ValueError('line %r of the docstring for %s has '
833 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000834 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000835
836
837######################################################################
838## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000839######################################################################
840
841class DocTestFinder:
842 """
843 A class used to extract the DocTests that are relevant to a given
844 object, from its docstring and the docstrings of its contained
845 objects. Doctests can currently be extracted from the following
846 object types: modules, functions, classes, methods, staticmethods,
847 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000848 """
849
Edward Lopera1ef6112004-08-09 16:14:41 +0000850 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000851 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000852 """
853 Create a new doctest finder.
854
Edward Lopera1ef6112004-08-09 16:14:41 +0000855 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000856 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000857 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000858 signature for this factory function should match the signature
859 of the DocTest constructor.
860
Tim Peters8485b562004-08-04 18:46:34 +0000861 If the optional argument `recurse` is false, then `find` will
862 only examine the given object, and not any contained objects.
863 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000864 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000865 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000866 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000867 # _namefilter is undocumented, and exists only for temporary backward-
868 # compatibility support of testmod's deprecated isprivate mess.
869 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000870
871 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000872 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000873 """
874 Return a list of the DocTests that are defined by the given
875 object's docstring, or by any of its contained objects'
876 docstrings.
877
878 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000879 the given object. If the module is not specified or is None, then
880 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000881 correct module. The object's module is used:
882
883 - As a default namespace, if `globs` is not specified.
884 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000885 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000886 - To find the name of the file containing the object.
887 - To help find the line number of the object within its
888 file.
889
Tim Petersf3f57472004-08-08 06:11:48 +0000890 Contained objects whose module does not match `module` are ignored.
891
892 If `module` is False, no attempt to find the module will be made.
893 This is obscure, of use mostly in tests: if `module` is False, or
894 is None but cannot be found automatically, then all objects are
895 considered to belong to the (non-existent) module, so all contained
896 objects will (recursively) be searched for doctests.
897
Tim Peters8485b562004-08-04 18:46:34 +0000898 The globals for each DocTest is formed by combining `globs`
899 and `extraglobs` (bindings in `extraglobs` override bindings
900 in `globs`). A new copy of the globals dictionary is created
901 for each DocTest. If `globs` is not specified, then it
902 defaults to the module's `__dict__`, if specified, or {}
903 otherwise. If `extraglobs` is not specified, then it defaults
904 to {}.
905
Tim Peters8485b562004-08-04 18:46:34 +0000906 """
907 # If name was not specified, then extract it from the object.
908 if name is None:
909 name = getattr(obj, '__name__', None)
910 if name is None:
911 raise ValueError("DocTestFinder.find: name must be given "
912 "when obj.__name__ doesn't exist: %r" %
913 (type(obj),))
914
915 # Find the module that contains the given object (if obj is
916 # a module, then module=obj.). Note: this may fail, in which
917 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000918 if module is False:
919 module = None
920 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000921 module = inspect.getmodule(obj)
922
923 # Read the module's source code. This is used by
924 # DocTestFinder._find_lineno to find the line number for a
925 # given object's docstring.
926 try:
927 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
928 source_lines = linecache.getlines(file)
929 if not source_lines:
930 source_lines = None
931 except TypeError:
932 source_lines = None
933
934 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000935 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000936 if module is None:
937 globs = {}
938 else:
939 globs = module.__dict__.copy()
940 else:
941 globs = globs.copy()
942 if extraglobs is not None:
943 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000944
Tim Peters8485b562004-08-04 18:46:34 +0000945 # Recursively expore `obj`, extracting DocTests.
946 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000947 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000948 return tests
949
950 def _filter(self, obj, prefix, base):
951 """
952 Return true if the given object should not be examined.
953 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000954 return (self._namefilter is not None and
955 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000956
957 def _from_module(self, module, object):
958 """
959 Return true if the given object is defined in the given
960 module.
961 """
962 if module is None:
963 return True
964 elif inspect.isfunction(object):
965 return module.__dict__ is object.func_globals
966 elif inspect.isclass(object):
967 return module.__name__ == object.__module__
968 elif inspect.getmodule(object) is not None:
969 return module is inspect.getmodule(object)
970 elif hasattr(object, '__module__'):
971 return module.__name__ == object.__module__
972 elif isinstance(object, property):
973 return True # [XX] no way not be sure.
974 else:
975 raise ValueError("object must be a class or function")
976
Tim Petersf3f57472004-08-08 06:11:48 +0000977 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000978 """
979 Find tests for the given object and any contained objects, and
980 add them to `tests`.
981 """
982 if self._verbose:
983 print 'Finding tests in %s' % name
984
985 # If we've already processed this object, then ignore it.
986 if id(obj) in seen:
987 return
988 seen[id(obj)] = 1
989
990 # Find a test for this object, and add it to the list of tests.
991 test = self._get_test(obj, name, module, globs, source_lines)
992 if test is not None:
993 tests.append(test)
994
995 # Look for tests in a module's contained objects.
996 if inspect.ismodule(obj) and self._recurse:
997 for valname, val in obj.__dict__.items():
998 # Check if this contained object should be ignored.
999 if self._filter(val, name, valname):
1000 continue
1001 valname = '%s.%s' % (name, valname)
1002 # Recurse to functions & classes.
1003 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +00001004 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001005 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001006 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001007
1008 # Look for tests in a module's __test__ dictionary.
1009 if inspect.ismodule(obj) and self._recurse:
1010 for valname, val in getattr(obj, '__test__', {}).items():
1011 if not isinstance(valname, basestring):
1012 raise ValueError("DocTestFinder.find: __test__ keys "
1013 "must be strings: %r" %
1014 (type(valname),))
1015 if not (inspect.isfunction(val) or inspect.isclass(val) or
1016 inspect.ismethod(val) or inspect.ismodule(val) or
1017 isinstance(val, basestring)):
1018 raise ValueError("DocTestFinder.find: __test__ values "
1019 "must be strings, functions, methods, "
1020 "classes, or modules: %r" %
1021 (type(val),))
1022 valname = '%s.%s' % (name, valname)
1023 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001024 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001025
1026 # Look for tests in a class's contained objects.
1027 if inspect.isclass(obj) and self._recurse:
1028 for valname, val in obj.__dict__.items():
1029 # Check if this contained object should be ignored.
1030 if self._filter(val, name, valname):
1031 continue
1032 # Special handling for staticmethod/classmethod.
1033 if isinstance(val, staticmethod):
1034 val = getattr(obj, valname)
1035 if isinstance(val, classmethod):
1036 val = getattr(obj, valname).im_func
1037
1038 # Recurse to methods, properties, and nested classes.
1039 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001040 isinstance(val, property)) and
1041 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001042 valname = '%s.%s' % (name, valname)
1043 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001044 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001045
1046 def _get_test(self, obj, name, module, globs, source_lines):
1047 """
1048 Return a DocTest for the given object, if it defines a docstring;
1049 otherwise, return None.
1050 """
1051 # Extract the object's docstring. If it doesn't have one,
1052 # then return None (no test for this object).
1053 if isinstance(obj, basestring):
1054 docstring = obj
1055 else:
1056 try:
1057 if obj.__doc__ is None:
1058 return None
1059 docstring = str(obj.__doc__)
1060 except (TypeError, AttributeError):
1061 return None
1062
1063 # Don't bother if the docstring is empty.
1064 if not docstring:
1065 return None
1066
1067 # Find the docstring's location in the file.
1068 lineno = self._find_lineno(obj, source_lines)
1069
1070 # Return a DocTest for this object.
1071 if module is None:
1072 filename = None
1073 else:
1074 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001075 if filename[-4:] in (".pyc", ".pyo"):
1076 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001077 return self._parser.get_doctest(docstring, globs, name,
1078 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001079
1080 def _find_lineno(self, obj, source_lines):
1081 """
1082 Return a line number of the given object's docstring. Note:
1083 this method assumes that the object has a docstring.
1084 """
1085 lineno = None
1086
1087 # Find the line number for modules.
1088 if inspect.ismodule(obj):
1089 lineno = 0
1090
1091 # Find the line number for classes.
1092 # Note: this could be fooled if a class is defined multiple
1093 # times in a single file.
1094 if inspect.isclass(obj):
1095 if source_lines is None:
1096 return None
1097 pat = re.compile(r'^\s*class\s*%s\b' %
1098 getattr(obj, '__name__', '-'))
1099 for i, line in enumerate(source_lines):
1100 if pat.match(line):
1101 lineno = i
1102 break
1103
1104 # Find the line number for functions & methods.
1105 if inspect.ismethod(obj): obj = obj.im_func
1106 if inspect.isfunction(obj): obj = obj.func_code
1107 if inspect.istraceback(obj): obj = obj.tb_frame
1108 if inspect.isframe(obj): obj = obj.f_code
1109 if inspect.iscode(obj):
1110 lineno = getattr(obj, 'co_firstlineno', None)-1
1111
1112 # Find the line number where the docstring starts. Assume
1113 # that it's the first line that begins with a quote mark.
1114 # Note: this could be fooled by a multiline function
1115 # signature, where a continuation line begins with a quote
1116 # mark.
1117 if lineno is not None:
1118 if source_lines is None:
1119 return lineno+1
1120 pat = re.compile('(^|.*:)\s*\w*("|\')')
1121 for lineno in range(lineno, len(source_lines)):
1122 if pat.match(source_lines[lineno]):
1123 return lineno
1124
1125 # We couldn't find the line number.
1126 return None
1127
1128######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001129## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001130######################################################################
1131
Tim Peters8485b562004-08-04 18:46:34 +00001132class DocTestRunner:
1133 """
1134 A class used to run DocTest test cases, and accumulate statistics.
1135 The `run` method is used to process a single DocTest case. It
1136 returns a tuple `(f, t)`, where `t` is the number of test cases
1137 tried, and `f` is the number of test cases that failed.
1138
1139 >>> tests = DocTestFinder().find(_TestClass)
1140 >>> runner = DocTestRunner(verbose=False)
1141 >>> for test in tests:
1142 ... print runner.run(test)
1143 (0, 2)
1144 (0, 1)
1145 (0, 2)
1146 (0, 2)
1147
1148 The `summarize` method prints a summary of all the test cases that
1149 have been run by the runner, and returns an aggregated `(f, t)`
1150 tuple:
1151
1152 >>> runner.summarize(verbose=1)
1153 4 items passed all tests:
1154 2 tests in _TestClass
1155 2 tests in _TestClass.__init__
1156 2 tests in _TestClass.get
1157 1 tests in _TestClass.square
1158 7 tests in 4 items.
1159 7 passed and 0 failed.
1160 Test passed.
1161 (0, 7)
1162
1163 The aggregated number of tried examples and failed examples is
1164 also available via the `tries` and `failures` attributes:
1165
1166 >>> runner.tries
1167 7
1168 >>> runner.failures
1169 0
1170
1171 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001172 by an `OutputChecker`. This comparison may be customized with a
1173 number of option flags; see the documentation for `testmod` for
1174 more information. If the option flags are insufficient, then the
1175 comparison may also be customized by passing a subclass of
1176 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001177
1178 The test runner's display output can be controlled in two ways.
1179 First, an output function (`out) can be passed to
1180 `TestRunner.run`; this function will be called with strings that
1181 should be displayed. It defaults to `sys.stdout.write`. If
1182 capturing the output is not sufficient, then the display output
1183 can be also customized by subclassing DocTestRunner, and
1184 overriding the methods `report_start`, `report_success`,
1185 `report_unexpected_exception`, and `report_failure`.
1186 """
1187 # This divider string is used to separate failure messages, and to
1188 # separate sections of the summary.
1189 DIVIDER = "*" * 70
1190
Edward Loper34fcb142004-08-09 02:45:41 +00001191 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001192 """
1193 Create a new test runner.
1194
Edward Loper34fcb142004-08-09 02:45:41 +00001195 Optional keyword arg `checker` is the `OutputChecker` that
1196 should be used to compare the expected outputs and actual
1197 outputs of doctest examples.
1198
Tim Peters8485b562004-08-04 18:46:34 +00001199 Optional keyword arg 'verbose' prints lots of stuff if true,
1200 only failures if false; by default, it's true iff '-v' is in
1201 sys.argv.
1202
1203 Optional argument `optionflags` can be used to control how the
1204 test runner compares expected output to actual output, and how
1205 it displays failures. See the documentation for `testmod` for
1206 more information.
1207 """
Edward Loper34fcb142004-08-09 02:45:41 +00001208 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001209 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001210 verbose = '-v' in sys.argv
1211 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001212 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001213 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001214
Tim Peters8485b562004-08-04 18:46:34 +00001215 # Keep track of the examples we've run.
1216 self.tries = 0
1217 self.failures = 0
1218 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001219
Tim Peters8485b562004-08-04 18:46:34 +00001220 # Create a fake output target for capturing doctest output.
1221 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001222
Tim Peters8485b562004-08-04 18:46:34 +00001223 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001224 # Reporting methods
1225 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001226
Tim Peters8485b562004-08-04 18:46:34 +00001227 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001228 """
Tim Peters8485b562004-08-04 18:46:34 +00001229 Report that the test runner is about to process the given
1230 example. (Only displays a message if verbose=True)
1231 """
1232 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001233 if example.want:
1234 out('Trying:\n' + _indent(example.source) +
1235 'Expecting:\n' + _indent(example.want))
1236 else:
1237 out('Trying:\n' + _indent(example.source) +
1238 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001239
Tim Peters8485b562004-08-04 18:46:34 +00001240 def report_success(self, out, test, example, got):
1241 """
1242 Report that the given example ran successfully. (Only
1243 displays a message if verbose=True)
1244 """
1245 if self._verbose:
1246 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001247
Tim Peters8485b562004-08-04 18:46:34 +00001248 def report_failure(self, out, test, example, got):
1249 """
1250 Report that the given example failed.
1251 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001252 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001253 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001254
Tim Peters8485b562004-08-04 18:46:34 +00001255 def report_unexpected_exception(self, out, test, example, exc_info):
1256 """
1257 Report that the given example raised an unexpected exception.
1258 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001259 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001260 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001261
Edward Loper8e4a34b2004-08-12 02:34:27 +00001262 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001263 out = [self.DIVIDER]
1264 if test.filename:
1265 if test.lineno is not None and example.lineno is not None:
1266 lineno = test.lineno + example.lineno + 1
1267 else:
1268 lineno = '?'
1269 out.append('File "%s", line %s, in %s' %
1270 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001271 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001272 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1273 out.append('Failed example:')
1274 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001275 out.append(_indent(source))
1276 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001277
Tim Peters8485b562004-08-04 18:46:34 +00001278 #/////////////////////////////////////////////////////////////////
1279 # DocTest Running
1280 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001281
Tim Peters8485b562004-08-04 18:46:34 +00001282 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001283 """
Tim Peters8485b562004-08-04 18:46:34 +00001284 Run the examples in `test`. Write the outcome of each example
1285 with one of the `DocTestRunner.report_*` methods, using the
1286 writer function `out`. `compileflags` is the set of compiler
1287 flags that should be used to execute examples. Return a tuple
1288 `(f, t)`, where `t` is the number of examples tried, and `f`
1289 is the number of examples that failed. The examples are run
1290 in the namespace `test.globs`.
1291 """
1292 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001293 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001294
1295 # Save the option flags (since option directives can be used
1296 # to modify them).
1297 original_optionflags = self.optionflags
1298
Tim Peters1fbf9c52004-09-04 17:21:02 +00001299 SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
1300
1301 check = self._checker.check_output
1302
Tim Peters8485b562004-08-04 18:46:34 +00001303 # Process each example.
Edward Loper2de91ba2004-08-27 02:07:46 +00001304 for examplenum, example in enumerate(test.examples):
1305
Edward Lopera89f88d2004-08-26 02:45:51 +00001306 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1307 # reporting after the first failure.
1308 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1309 failures > 0)
1310
Edward Loper74bca7a2004-08-12 02:27:44 +00001311 # Merge in the example's options.
1312 self.optionflags = original_optionflags
1313 if example.options:
1314 for (optionflag, val) in example.options.items():
1315 if val:
1316 self.optionflags |= optionflag
1317 else:
1318 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001319
1320 # Record that we started this example.
1321 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001322 if not quiet:
1323 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001324
Edward Loper2de91ba2004-08-27 02:07:46 +00001325 # Use a special filename for compile(), so we can retrieve
1326 # the source code during interactive debugging (see
1327 # __patched_linecache_getlines).
1328 filename = '<doctest %s[%d]>' % (test.name, examplenum)
1329
Tim Peters8485b562004-08-04 18:46:34 +00001330 # Run the example in the given context (globs), and record
1331 # any exception that gets raised. (But don't intercept
1332 # keyboard interrupts.)
1333 try:
Tim Peters208ca702004-08-09 04:12:36 +00001334 # Don't blink! This is where the user's code gets run.
Edward Loper2de91ba2004-08-27 02:07:46 +00001335 exec compile(example.source, filename, "single",
Tim Peters8485b562004-08-04 18:46:34 +00001336 compileflags, 1) in test.globs
Edward Loper2de91ba2004-08-27 02:07:46 +00001337 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001338 exception = None
1339 except KeyboardInterrupt:
1340 raise
1341 except:
1342 exception = sys.exc_info()
Edward Loper2de91ba2004-08-27 02:07:46 +00001343 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001344
Tim Peters208ca702004-08-09 04:12:36 +00001345 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001346 self._fakeout.truncate(0)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001347 outcome = FAILURE # guilty until proved innocent or insane
Tim Peters8485b562004-08-04 18:46:34 +00001348
1349 # If the example executed without raising any exceptions,
Tim Peters1fbf9c52004-09-04 17:21:02 +00001350 # verify its output.
Tim Peters8485b562004-08-04 18:46:34 +00001351 if exception is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001352 if check(example.want, got, self.optionflags):
1353 outcome = SUCCESS
Tim Peters8485b562004-08-04 18:46:34 +00001354
Tim Peters1fbf9c52004-09-04 17:21:02 +00001355 # The example raised an exception: check if it was expected.
Tim Peters8485b562004-08-04 18:46:34 +00001356 else:
1357 exc_info = sys.exc_info()
1358 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
Tim Peters1fbf9c52004-09-04 17:21:02 +00001359 if not quiet:
1360 got += _exception_traceback(exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001361
Tim Peters1fbf9c52004-09-04 17:21:02 +00001362 # If `example.exc_msg` is None, then we weren't expecting
1363 # an exception.
Edward Lopera6b68322004-08-26 00:05:43 +00001364 if example.exc_msg is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001365 outcome = BOOM
1366
1367 # We expected an exception: see whether it matches.
1368 elif check(example.exc_msg, exc_msg, self.optionflags):
1369 outcome = SUCCESS
1370
1371 # Another chance if they didn't care about the detail.
1372 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
1373 m1 = re.match(r'[^:]*:', example.exc_msg)
1374 m2 = re.match(r'[^:]*:', exc_msg)
1375 if m1 and m2 and check(m1.group(0), m2.group(0),
1376 self.optionflags):
1377 outcome = SUCCESS
1378
1379 # Report the outcome.
1380 if outcome is SUCCESS:
1381 if not quiet:
1382 self.report_success(out, test, example, got)
1383 elif outcome is FAILURE:
1384 if not quiet:
1385 self.report_failure(out, test, example, got)
1386 failures += 1
1387 elif outcome is BOOM:
1388 if not quiet:
1389 self.report_unexpected_exception(out, test, example,
1390 exc_info)
1391 failures += 1
1392 else:
1393 assert False, ("unknown outcome", outcome)
Tim Peters8485b562004-08-04 18:46:34 +00001394
1395 # Restore the option flags (in case they were modified)
1396 self.optionflags = original_optionflags
1397
1398 # Record and return the number of failures and tries.
1399 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001400 return failures, tries
1401
Tim Peters8485b562004-08-04 18:46:34 +00001402 def __record_outcome(self, test, f, t):
1403 """
1404 Record the fact that the given DocTest (`test`) generated `f`
1405 failures out of `t` tried examples.
1406 """
1407 f2, t2 = self._name2ft.get(test.name, (0,0))
1408 self._name2ft[test.name] = (f+f2, t+t2)
1409 self.failures += f
1410 self.tries += t
1411
Edward Loper2de91ba2004-08-27 02:07:46 +00001412 __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1413 r'(?P<name>[\w\.]+)'
1414 r'\[(?P<examplenum>\d+)\]>$')
1415 def __patched_linecache_getlines(self, filename):
1416 m = self.__LINECACHE_FILENAME_RE.match(filename)
1417 if m and m.group('name') == self.test.name:
1418 example = self.test.examples[int(m.group('examplenum'))]
1419 return example.source.splitlines(True)
1420 else:
1421 return self.save_linecache_getlines(filename)
1422
Tim Peters8485b562004-08-04 18:46:34 +00001423 def run(self, test, compileflags=None, out=None, clear_globs=True):
1424 """
1425 Run the examples in `test`, and display the results using the
1426 writer function `out`.
1427
1428 The examples are run in the namespace `test.globs`. If
1429 `clear_globs` is true (the default), then this namespace will
1430 be cleared after the test runs, to help with garbage
1431 collection. If you would like to examine the namespace after
1432 the test completes, then use `clear_globs=False`.
1433
1434 `compileflags` gives the set of flags that should be used by
1435 the Python compiler when running the examples. If not
1436 specified, then it will default to the set of future-import
1437 flags that apply to `globs`.
1438
1439 The output of each example is checked using
1440 `DocTestRunner.check_output`, and the results are formatted by
1441 the `DocTestRunner.report_*` methods.
1442 """
Edward Loper2de91ba2004-08-27 02:07:46 +00001443 self.test = test
1444
Tim Peters8485b562004-08-04 18:46:34 +00001445 if compileflags is None:
1446 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001447
Tim Peters6c542b72004-08-09 16:43:36 +00001448 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001449 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001450 out = save_stdout.write
1451 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001452
Edward Loper2de91ba2004-08-27 02:07:46 +00001453 # Patch pdb.set_trace to restore sys.stdout during interactive
1454 # debugging (so it's not still redirected to self._fakeout).
1455 # Note that the interactive output will go to *our*
1456 # save_stdout, even if that's not the real sys.stdout; this
1457 # allows us to write test cases for the set_trace behavior.
Tim Peters6c542b72004-08-09 16:43:36 +00001458 save_set_trace = pdb.set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001459 self.debugger = _OutputRedirectingPdb(save_stdout)
1460 self.debugger.reset()
1461 pdb.set_trace = self.debugger.set_trace
1462
1463 # Patch linecache.getlines, so we can see the example's source
1464 # when we're inside the debugger.
1465 self.save_linecache_getlines = linecache.getlines
1466 linecache.getlines = self.__patched_linecache_getlines
1467
Tim Peters8485b562004-08-04 18:46:34 +00001468 try:
Tim Peters8485b562004-08-04 18:46:34 +00001469 return self.__run(test, compileflags, out)
1470 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001471 sys.stdout = save_stdout
1472 pdb.set_trace = save_set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001473 linecache.getlines = self.save_linecache_getlines
Tim Peters8485b562004-08-04 18:46:34 +00001474 if clear_globs:
1475 test.globs.clear()
1476
1477 #/////////////////////////////////////////////////////////////////
1478 # Summarization
1479 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001480 def summarize(self, verbose=None):
1481 """
Tim Peters8485b562004-08-04 18:46:34 +00001482 Print a summary of all the test cases that have been run by
1483 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1484 the total number of failed examples, and `t` is the total
1485 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001486
Tim Peters8485b562004-08-04 18:46:34 +00001487 The optional `verbose` argument controls how detailed the
1488 summary is. If the verbosity is not specified, then the
1489 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001490 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001491 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001492 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001493 notests = []
1494 passed = []
1495 failed = []
1496 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001497 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001498 name, (f, t) = x
1499 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001500 totalt += t
1501 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001502 if t == 0:
1503 notests.append(name)
1504 elif f == 0:
1505 passed.append( (name, t) )
1506 else:
1507 failed.append(x)
1508 if verbose:
1509 if notests:
1510 print len(notests), "items had no tests:"
1511 notests.sort()
1512 for thing in notests:
1513 print " ", thing
1514 if passed:
1515 print len(passed), "items passed all tests:"
1516 passed.sort()
1517 for thing, count in passed:
1518 print " %3d tests in %s" % (count, thing)
1519 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001520 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001521 print len(failed), "items had failures:"
1522 failed.sort()
1523 for thing, (f, t) in failed:
1524 print " %3d of %3d in %s" % (f, t, thing)
1525 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001526 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001527 print totalt - totalf, "passed and", totalf, "failed."
1528 if totalf:
1529 print "***Test Failed***", totalf, "failures."
1530 elif verbose:
1531 print "Test passed."
1532 return totalf, totalt
1533
Edward Loper34fcb142004-08-09 02:45:41 +00001534class OutputChecker:
1535 """
1536 A class used to check the whether the actual output from a doctest
1537 example matches the expected output. `OutputChecker` defines two
1538 methods: `check_output`, which compares a given pair of outputs,
1539 and returns true if they match; and `output_difference`, which
1540 returns a string describing the differences between two outputs.
1541 """
1542 def check_output(self, want, got, optionflags):
1543 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001544 Return True iff the actual output from an example (`got`)
1545 matches the expected output (`want`). These strings are
1546 always considered to match if they are identical; but
1547 depending on what option flags the test runner is using,
1548 several non-exact match types are also possible. See the
1549 documentation for `TestRunner` for more information about
1550 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001551 """
1552 # Handle the common case first, for efficiency:
1553 # if they're string-identical, always return true.
1554 if got == want:
1555 return True
1556
1557 # The values True and False replaced 1 and 0 as the return
1558 # value for boolean comparisons in Python 2.3.
1559 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1560 if (got,want) == ("True\n", "1\n"):
1561 return True
1562 if (got,want) == ("False\n", "0\n"):
1563 return True
1564
1565 # <BLANKLINE> can be used as a special sequence to signify a
1566 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1567 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1568 # Replace <BLANKLINE> in want with a blank line.
1569 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1570 '', want)
1571 # If a line in got contains only spaces, then remove the
1572 # spaces.
1573 got = re.sub('(?m)^\s*?$', '', got)
1574 if got == want:
1575 return True
1576
1577 # This flag causes doctest to ignore any differences in the
1578 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001579 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001580 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001581 got = ' '.join(got.split())
1582 want = ' '.join(want.split())
1583 if got == want:
1584 return True
1585
1586 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001587 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001588 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001589 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001590 return True
1591
1592 # We didn't find any match; return false.
1593 return False
1594
Tim Petersc6cbab02004-08-22 19:43:28 +00001595 # Should we do a fancy diff?
1596 def _do_a_fancy_diff(self, want, got, optionflags):
1597 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001598 if not optionflags & (REPORT_UDIFF |
1599 REPORT_CDIFF |
1600 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001601 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001602
Tim Petersc6cbab02004-08-22 19:43:28 +00001603 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001604 # too hard ... or maybe not. In two real-life failures Tim saw,
1605 # a diff was a major help anyway, so this is commented out.
1606 # [todo] _ellipsis_match() knows which pieces do and don't match,
1607 # and could be the basis for a kick-ass diff in this case.
1608 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1609 ## return False
1610
Tim Petersc6cbab02004-08-22 19:43:28 +00001611 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001612 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001613 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001614 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001615
Tim Petersc6cbab02004-08-22 19:43:28 +00001616 # The other diff types need at least a few lines to be helpful.
1617 return want.count('\n') > 2 and got.count('\n') > 2
1618
Edward Loperca9111e2004-08-26 03:00:24 +00001619 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001620 """
1621 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001622 expected output for a given example (`example`) and the actual
1623 output (`got`). `optionflags` is the set of option flags used
1624 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001625 """
Edward Loperca9111e2004-08-26 03:00:24 +00001626 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001627 # If <BLANKLINE>s are being used, then replace blank lines
1628 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001629 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001630 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001631
Tim Peters5b799c12004-08-26 05:21:59 +00001632 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001633 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001634 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001635 want_lines = want.splitlines(True) # True == keep line ends
1636 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001637 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001638 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001639 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1640 diff = list(diff)[2:] # strip the diff header
1641 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001642 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001643 diff = difflib.context_diff(want_lines, got_lines, n=2)
1644 diff = list(diff)[2:] # strip the diff header
1645 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001646 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001647 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1648 diff = list(engine.compare(want_lines, got_lines))
1649 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001650 else:
1651 assert 0, 'Bad diff option'
1652 # Remove trailing whitespace on diff output.
1653 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001654 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001655
1656 # If we're not using diff, then simply list the expected
1657 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001658 if want and got:
1659 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1660 elif want:
1661 return 'Expected:\n%sGot nothing\n' % _indent(want)
1662 elif got:
1663 return 'Expected nothing\nGot:\n%s' % _indent(got)
1664 else:
1665 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001666
Tim Peters19397e52004-08-06 22:02:59 +00001667class DocTestFailure(Exception):
1668 """A DocTest example has failed in debugging mode.
1669
1670 The exception instance has variables:
1671
1672 - test: the DocTest object being run
1673
1674 - excample: the Example object that failed
1675
1676 - got: the actual output
1677 """
1678 def __init__(self, test, example, got):
1679 self.test = test
1680 self.example = example
1681 self.got = got
1682
1683 def __str__(self):
1684 return str(self.test)
1685
1686class UnexpectedException(Exception):
1687 """A DocTest example has encountered an unexpected exception
1688
1689 The exception instance has variables:
1690
1691 - test: the DocTest object being run
1692
1693 - excample: the Example object that failed
1694
1695 - exc_info: the exception info
1696 """
1697 def __init__(self, test, example, exc_info):
1698 self.test = test
1699 self.example = example
1700 self.exc_info = exc_info
1701
1702 def __str__(self):
1703 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001704
Tim Peters19397e52004-08-06 22:02:59 +00001705class DebugRunner(DocTestRunner):
1706 r"""Run doc tests but raise an exception as soon as there is a failure.
1707
1708 If an unexpected exception occurs, an UnexpectedException is raised.
1709 It contains the test, the example, and the original exception:
1710
1711 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001712 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1713 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001714 >>> try:
1715 ... runner.run(test)
1716 ... except UnexpectedException, failure:
1717 ... pass
1718
1719 >>> failure.test is test
1720 True
1721
1722 >>> failure.example.want
1723 '42\n'
1724
1725 >>> exc_info = failure.exc_info
1726 >>> raise exc_info[0], exc_info[1], exc_info[2]
1727 Traceback (most recent call last):
1728 ...
1729 KeyError
1730
1731 We wrap the original exception to give the calling application
1732 access to the test and example information.
1733
1734 If the output doesn't match, then a DocTestFailure is raised:
1735
Edward Lopera1ef6112004-08-09 16:14:41 +00001736 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001737 ... >>> x = 1
1738 ... >>> x
1739 ... 2
1740 ... ''', {}, 'foo', 'foo.py', 0)
1741
1742 >>> try:
1743 ... runner.run(test)
1744 ... except DocTestFailure, failure:
1745 ... pass
1746
1747 DocTestFailure objects provide access to the test:
1748
1749 >>> failure.test is test
1750 True
1751
1752 As well as to the example:
1753
1754 >>> failure.example.want
1755 '2\n'
1756
1757 and the actual output:
1758
1759 >>> failure.got
1760 '1\n'
1761
1762 If a failure or error occurs, the globals are left intact:
1763
1764 >>> del test.globs['__builtins__']
1765 >>> test.globs
1766 {'x': 1}
1767
Edward Lopera1ef6112004-08-09 16:14:41 +00001768 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001769 ... >>> x = 2
1770 ... >>> raise KeyError
1771 ... ''', {}, 'foo', 'foo.py', 0)
1772
1773 >>> runner.run(test)
1774 Traceback (most recent call last):
1775 ...
1776 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001777
Tim Peters19397e52004-08-06 22:02:59 +00001778 >>> del test.globs['__builtins__']
1779 >>> test.globs
1780 {'x': 2}
1781
1782 But the globals are cleared if there is no error:
1783
Edward Lopera1ef6112004-08-09 16:14:41 +00001784 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001785 ... >>> x = 2
1786 ... ''', {}, 'foo', 'foo.py', 0)
1787
1788 >>> runner.run(test)
1789 (0, 1)
1790
1791 >>> test.globs
1792 {}
1793
1794 """
1795
1796 def run(self, test, compileflags=None, out=None, clear_globs=True):
1797 r = DocTestRunner.run(self, test, compileflags, out, False)
1798 if clear_globs:
1799 test.globs.clear()
1800 return r
1801
1802 def report_unexpected_exception(self, out, test, example, exc_info):
1803 raise UnexpectedException(test, example, exc_info)
1804
1805 def report_failure(self, out, test, example, got):
1806 raise DocTestFailure(test, example, got)
1807
Tim Peters8485b562004-08-04 18:46:34 +00001808######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001809## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001810######################################################################
1811# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001812
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001813def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001814 report=True, optionflags=0, extraglobs=None,
1815 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001816 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001817 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001818
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001819 Test examples in docstrings in functions and classes reachable
1820 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001821 with m.__doc__. Unless isprivate is specified, private names
1822 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001823
1824 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001825 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001826 function and class docstrings are tested even if the name is private;
1827 strings are tested directly, as if they were docstrings.
1828
1829 Return (#failures, #tests).
1830
1831 See doctest.__doc__ for an overview.
1832
1833 Optional keyword arg "name" gives the name of the module; by default
1834 use m.__name__.
1835
1836 Optional keyword arg "globs" gives a dict to be used as the globals
1837 when executing examples; by default, use m.__dict__. A copy of this
1838 dict is actually used for each docstring, so that each docstring's
1839 examples start with a clean slate.
1840
Tim Peters8485b562004-08-04 18:46:34 +00001841 Optional keyword arg "extraglobs" gives a dictionary that should be
1842 merged into the globals that are used to execute examples. By
1843 default, no extra globals are used. This is new in 2.4.
1844
Tim Peters8a7d2d52001-01-16 07:10:57 +00001845 Optional keyword arg "verbose" prints lots of stuff if true, prints
1846 only failures if false; by default, it's true iff "-v" is in sys.argv.
1847
Tim Peters8a7d2d52001-01-16 07:10:57 +00001848 Optional keyword arg "report" prints a summary at the end when true,
1849 else prints nothing at the end. In verbose mode, the summary is
1850 detailed, else very brief (in fact, empty if all tests passed).
1851
Tim Peters6ebe61f2003-06-27 20:48:05 +00001852 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001853 and defaults to 0. This is new in 2.3. Possible values (see the
1854 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001855
1856 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001857 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001858 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001859 ELLIPSIS
Edward Loper71f55af2004-08-26 01:41:51 +00001860 REPORT_UDIFF
1861 REPORT_CDIFF
1862 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001863 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001864
1865 Optional keyword arg "raise_on_error" raises an exception on the
1866 first unexpected exception or failure. This allows failures to be
1867 post-mortem debugged.
1868
Tim Petersf727c6c2004-08-08 01:48:59 +00001869 Deprecated in Python 2.4:
1870 Optional keyword arg "isprivate" specifies a function used to
1871 determine whether a name is private. The default function is
1872 treat all functions as public. Optionally, "isprivate" can be
1873 set to doctest.is_private to skip over functions marked as private
1874 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001875 """
1876
1877 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001878 Advanced tomfoolery: testmod runs methods of a local instance of
1879 class doctest.Tester, then merges the results into (or creates)
1880 global Tester instance doctest.master. Methods of doctest.master
1881 can be called directly too, if you want to do something unusual.
1882 Passing report=0 to testmod is especially useful then, to delay
1883 displaying a summary. Invoke doctest.master.summarize(verbose)
1884 when you're done fiddling.
1885 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001886 if isprivate is not None:
1887 warnings.warn("the isprivate argument is deprecated; "
1888 "examine DocTestFinder.find() lists instead",
1889 DeprecationWarning)
1890
Tim Peters8485b562004-08-04 18:46:34 +00001891 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001892 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001893 # DWA - m will still be None if this wasn't invoked from the command
1894 # line, in which case the following TypeError is about as good an error
1895 # as we should expect
1896 m = sys.modules.get('__main__')
1897
Tim Peters8485b562004-08-04 18:46:34 +00001898 # Check that we were actually given a module.
1899 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001900 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001901
1902 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001903 if name is None:
1904 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001905
1906 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001907 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001908
1909 if raise_on_error:
1910 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1911 else:
1912 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1913
Tim Peters8485b562004-08-04 18:46:34 +00001914 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1915 runner.run(test)
1916
Tim Peters8a7d2d52001-01-16 07:10:57 +00001917 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001918 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001919
Tim Peters8485b562004-08-04 18:46:34 +00001920 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001921
Tim Peters8485b562004-08-04 18:46:34 +00001922def run_docstring_examples(f, globs, verbose=False, name="NoName",
1923 compileflags=None, optionflags=0):
1924 """
1925 Test examples in the given object's docstring (`f`), using `globs`
1926 as globals. Optional argument `name` is used in failure messages.
1927 If the optional argument `verbose` is true, then generate output
1928 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001929
Tim Peters8485b562004-08-04 18:46:34 +00001930 `compileflags` gives the set of flags that should be used by the
1931 Python compiler when running the examples. If not specified, then
1932 it will default to the set of future-import flags that apply to
1933 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001934
Tim Peters8485b562004-08-04 18:46:34 +00001935 Optional keyword arg `optionflags` specifies options for the
1936 testing and output. See the documentation for `testmod` for more
1937 information.
1938 """
1939 # Find, parse, and run all tests in the given module.
1940 finder = DocTestFinder(verbose=verbose, recurse=False)
1941 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1942 for test in finder.find(f, name, globs=globs):
1943 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001944
Tim Peters8485b562004-08-04 18:46:34 +00001945######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001946## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001947######################################################################
1948# This is provided only for backwards compatibility. It's not
1949# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001950
Tim Peters8485b562004-08-04 18:46:34 +00001951class Tester:
1952 def __init__(self, mod=None, globs=None, verbose=None,
1953 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001954
1955 warnings.warn("class Tester is deprecated; "
1956 "use class doctest.DocTestRunner instead",
1957 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001958 if mod is None and globs is None:
1959 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters4be7a922004-09-12 22:39:46 +00001960 if mod is not None and not inspect.ismodule(mod):
Tim Peters8485b562004-08-04 18:46:34 +00001961 raise TypeError("Tester.__init__: mod must be a module; %r" %
1962 (mod,))
1963 if globs is None:
1964 globs = mod.__dict__
1965 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001966
Tim Peters8485b562004-08-04 18:46:34 +00001967 self.verbose = verbose
1968 self.isprivate = isprivate
1969 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001970 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001971 self.testrunner = DocTestRunner(verbose=verbose,
1972 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001973
Tim Peters8485b562004-08-04 18:46:34 +00001974 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001975 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001976 if self.verbose:
1977 print "Running string", name
1978 (f,t) = self.testrunner.run(test)
1979 if self.verbose:
1980 print f, "of", t, "examples failed in string", name
1981 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001982
Tim Petersf3f57472004-08-08 06:11:48 +00001983 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001984 f = t = 0
1985 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001986 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001987 for test in tests:
1988 (f2, t2) = self.testrunner.run(test)
1989 (f,t) = (f+f2, t+t2)
1990 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001991
Tim Peters8485b562004-08-04 18:46:34 +00001992 def rundict(self, d, name, module=None):
1993 import new
1994 m = new.module(name)
1995 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001996 if module is None:
1997 module = False
1998 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001999
Tim Peters8485b562004-08-04 18:46:34 +00002000 def run__test__(self, d, name):
2001 import new
2002 m = new.module(name)
2003 m.__test__ = d
Tim Peters9661f9a2004-09-12 22:45:17 +00002004 return self.rundoc(m, name)
Tim Petersdb3756d2003-06-29 05:30:48 +00002005
Tim Peters8485b562004-08-04 18:46:34 +00002006 def summarize(self, verbose=None):
2007 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00002008
Tim Peters8485b562004-08-04 18:46:34 +00002009 def merge(self, other):
2010 d = self.testrunner._name2ft
2011 for name, (f, t) in other.testrunner._name2ft.items():
2012 if name in d:
2013 print "*** Tester.merge: '" + name + "' in both" \
2014 " testers; summing outcomes."
2015 f2, t2 = d[name]
2016 f = f + f2
2017 t = t + t2
2018 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00002019
Tim Peters8485b562004-08-04 18:46:34 +00002020######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002021## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002022######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002023
Jim Fultonf54bad42004-08-28 14:57:56 +00002024_unittest_reportflags = 0
Tim Peters38330fe2004-08-30 16:19:24 +00002025
Jim Fultonf54bad42004-08-28 14:57:56 +00002026def set_unittest_reportflags(flags):
Tim Peters38330fe2004-08-30 16:19:24 +00002027 """Sets the unittest option flags.
Jim Fultonf54bad42004-08-28 14:57:56 +00002028
2029 The old flag is returned so that a runner could restore the old
2030 value if it wished to:
2031
2032 >>> old = _unittest_reportflags
2033 >>> set_unittest_reportflags(REPORT_NDIFF |
2034 ... REPORT_ONLY_FIRST_FAILURE) == old
2035 True
2036
2037 >>> import doctest
2038 >>> doctest._unittest_reportflags == (REPORT_NDIFF |
2039 ... REPORT_ONLY_FIRST_FAILURE)
2040 True
Tim Petersdf7a2082004-08-29 00:38:17 +00002041
Jim Fultonf54bad42004-08-28 14:57:56 +00002042 Only reporting flags can be set:
2043
2044 >>> set_unittest_reportflags(ELLIPSIS)
2045 Traceback (most recent call last):
2046 ...
Tim Peters38330fe2004-08-30 16:19:24 +00002047 ValueError: ('Only reporting flags allowed', 8)
Jim Fultonf54bad42004-08-28 14:57:56 +00002048
2049 >>> set_unittest_reportflags(old) == (REPORT_NDIFF |
2050 ... REPORT_ONLY_FIRST_FAILURE)
2051 True
Jim Fultonf54bad42004-08-28 14:57:56 +00002052 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002053 global _unittest_reportflags
Tim Peters38330fe2004-08-30 16:19:24 +00002054
2055 if (flags & REPORTING_FLAGS) != flags:
2056 raise ValueError("Only reporting flags allowed", flags)
Jim Fultonf54bad42004-08-28 14:57:56 +00002057 old = _unittest_reportflags
2058 _unittest_reportflags = flags
2059 return old
Tim Petersdf7a2082004-08-29 00:38:17 +00002060
Jim Fultonf54bad42004-08-28 14:57:56 +00002061
Tim Peters19397e52004-08-06 22:02:59 +00002062class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002063
Edward Loper34fcb142004-08-09 02:45:41 +00002064 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2065 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002066
Jim Fultona643b652004-07-14 19:06:50 +00002067 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002068 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002069 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002070 self._dt_test = test
2071 self._dt_setUp = setUp
2072 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002073
Jim Fultona643b652004-07-14 19:06:50 +00002074 def setUp(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002075 test = self._dt_test
Tim Petersdf7a2082004-08-29 00:38:17 +00002076
Tim Peters19397e52004-08-06 22:02:59 +00002077 if self._dt_setUp is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002078 self._dt_setUp(test)
Jim Fultona643b652004-07-14 19:06:50 +00002079
2080 def tearDown(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002081 test = self._dt_test
2082
Tim Peters19397e52004-08-06 22:02:59 +00002083 if self._dt_tearDown is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002084 self._dt_tearDown(test)
2085
2086 test.globs.clear()
Jim Fultona643b652004-07-14 19:06:50 +00002087
2088 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002089 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002090 old = sys.stdout
2091 new = StringIO()
Jim Fultonf54bad42004-08-28 14:57:56 +00002092 optionflags = self._dt_optionflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002093
Tim Peters38330fe2004-08-30 16:19:24 +00002094 if not (optionflags & REPORTING_FLAGS):
Jim Fultonf54bad42004-08-28 14:57:56 +00002095 # The option flags don't include any reporting flags,
2096 # so add the default reporting flags
2097 optionflags |= _unittest_reportflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002098
Jim Fultonf54bad42004-08-28 14:57:56 +00002099 runner = DocTestRunner(optionflags=optionflags,
Edward Loper34fcb142004-08-09 02:45:41 +00002100 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002101
Jim Fultona643b652004-07-14 19:06:50 +00002102 try:
Tim Peters19397e52004-08-06 22:02:59 +00002103 runner.DIVIDER = "-"*70
Jim Fultonf54bad42004-08-28 14:57:56 +00002104 failures, tries = runner.run(
2105 test, out=new.write, clear_globs=False)
Jim Fultona643b652004-07-14 19:06:50 +00002106 finally:
2107 sys.stdout = old
2108
2109 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002110 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002111
Tim Peters19397e52004-08-06 22:02:59 +00002112 def format_failure(self, err):
2113 test = self._dt_test
2114 if test.lineno is None:
2115 lineno = 'unknown line number'
2116 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002117 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002118 lname = '.'.join(test.name.split('.')[-1:])
2119 return ('Failed doctest test for %s\n'
2120 ' File "%s", line %s, in %s\n\n%s'
2121 % (test.name, test.filename, lineno, lname, err)
2122 )
2123
2124 def debug(self):
2125 r"""Run the test case without results and without catching exceptions
2126
2127 The unit test framework includes a debug method on test cases
2128 and test suites to support post-mortem debugging. The test code
2129 is run in such a way that errors are not caught. This way a
2130 caller can catch the errors and initiate post-mortem debugging.
2131
2132 The DocTestCase provides a debug method that raises
2133 UnexpectedException errors if there is an unexepcted
2134 exception:
2135
Edward Lopera1ef6112004-08-09 16:14:41 +00002136 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002137 ... {}, 'foo', 'foo.py', 0)
2138 >>> case = DocTestCase(test)
2139 >>> try:
2140 ... case.debug()
2141 ... except UnexpectedException, failure:
2142 ... pass
2143
2144 The UnexpectedException contains the test, the example, and
2145 the original exception:
2146
2147 >>> failure.test is test
2148 True
2149
2150 >>> failure.example.want
2151 '42\n'
2152
2153 >>> exc_info = failure.exc_info
2154 >>> raise exc_info[0], exc_info[1], exc_info[2]
2155 Traceback (most recent call last):
2156 ...
2157 KeyError
2158
2159 If the output doesn't match, then a DocTestFailure is raised:
2160
Edward Lopera1ef6112004-08-09 16:14:41 +00002161 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002162 ... >>> x = 1
2163 ... >>> x
2164 ... 2
2165 ... ''', {}, 'foo', 'foo.py', 0)
2166 >>> case = DocTestCase(test)
2167
2168 >>> try:
2169 ... case.debug()
2170 ... except DocTestFailure, failure:
2171 ... pass
2172
2173 DocTestFailure objects provide access to the test:
2174
2175 >>> failure.test is test
2176 True
2177
2178 As well as to the example:
2179
2180 >>> failure.example.want
2181 '2\n'
2182
2183 and the actual output:
2184
2185 >>> failure.got
2186 '1\n'
2187
2188 """
2189
Jim Fultonf54bad42004-08-28 14:57:56 +00002190 self.setUp()
Edward Loper34fcb142004-08-09 02:45:41 +00002191 runner = DebugRunner(optionflags=self._dt_optionflags,
2192 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002193 runner.run(self._dt_test)
Jim Fultonf54bad42004-08-28 14:57:56 +00002194 self.tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002195
2196 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002197 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002198
2199 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002200 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002201 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2202
2203 __str__ = __repr__
2204
2205 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002206 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002207
Jim Fultonf54bad42004-08-28 14:57:56 +00002208def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2209 **options):
Tim Peters8485b562004-08-04 18:46:34 +00002210 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002211 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002212
Tim Peters19397e52004-08-06 22:02:59 +00002213 This converts each documentation string in a module that
2214 contains doctest tests to a unittest test case. If any of the
2215 tests in a doc string fail, then the test case fails. An exception
2216 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002217 (sometimes approximate) line number.
2218
Tim Peters19397e52004-08-06 22:02:59 +00002219 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002220 can be either a module or a module name.
2221
2222 If no argument is given, the calling module is used.
Jim Fultonf54bad42004-08-28 14:57:56 +00002223
2224 A number of options may be provided as keyword arguments:
2225
2226 package
2227 The name of a Python package. Text-file paths will be
2228 interpreted relative to the directory containing this package.
2229 The package may be supplied as a package object or as a dotted
2230 package name.
2231
2232 setUp
2233 The name of a set-up function. This is called before running the
2234 tests in each file. The setUp function will be passed a DocTest
2235 object. The setUp function can access the test globals as the
2236 globs attribute of the test passed.
2237
2238 tearDown
2239 The name of a tear-down function. This is called after running the
2240 tests in each file. The tearDown function will be passed a DocTest
2241 object. The tearDown function can access the test globals as the
2242 globs attribute of the test passed.
2243
2244 globs
2245 A dictionary containing initial global variables for the tests.
2246
2247 optionflags
2248 A set of doctest option flags expressed as an integer.
Jim Fultona643b652004-07-14 19:06:50 +00002249 """
Jim Fultona643b652004-07-14 19:06:50 +00002250
Tim Peters8485b562004-08-04 18:46:34 +00002251 if test_finder is None:
2252 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002253
Tim Peters19397e52004-08-06 22:02:59 +00002254 module = _normalize_module(module)
2255 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2256 if globs is None:
2257 globs = module.__dict__
Jim Fultonf54bad42004-08-28 14:57:56 +00002258 if not tests:
2259 # Why do we want to do this? Because it reveals a bug that might
2260 # otherwise be hidden.
Tim Peters19397e52004-08-06 22:02:59 +00002261 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002262
2263 tests.sort()
2264 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002265 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002266 if len(test.examples) == 0:
2267 continue
Tim Peters8485b562004-08-04 18:46:34 +00002268 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002269 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002270 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002271 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002272 test.filename = filename
Jim Fultonf54bad42004-08-28 14:57:56 +00002273 suite.addTest(DocTestCase(test, **options))
Tim Peters19397e52004-08-06 22:02:59 +00002274
2275 return suite
2276
2277class DocFileCase(DocTestCase):
2278
2279 def id(self):
2280 return '_'.join(self._dt_test.name.split('.'))
2281
2282 def __repr__(self):
2283 return self._dt_test.filename
2284 __str__ = __repr__
2285
2286 def format_failure(self, err):
2287 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2288 % (self._dt_test.name, self._dt_test.filename, err)
2289 )
2290
Jim Fultonf54bad42004-08-28 14:57:56 +00002291def DocFileTest(path, package=None, globs=None, **options):
Tim Peters19397e52004-08-06 22:02:59 +00002292 package = _normalize_module(package)
2293 name = path.split('/')[-1]
2294 dir = os.path.split(package.__file__)[0]
2295 path = os.path.join(dir, *(path.split('/')))
2296 doc = open(path).read()
2297
2298 if globs is None:
2299 globs = {}
2300
Edward Lopera1ef6112004-08-09 16:14:41 +00002301 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002302
Jim Fultonf54bad42004-08-28 14:57:56 +00002303 return DocFileCase(test, **options)
Tim Peters19397e52004-08-06 22:02:59 +00002304
2305def DocFileSuite(*paths, **kw):
2306 """Creates a suite of doctest files.
2307
2308 One or more text file paths are given as strings. These should
2309 use "/" characters to separate path segments. Paths are relative
2310 to the directory of the calling module, or relative to the package
2311 passed as a keyword argument.
2312
2313 A number of options may be provided as keyword arguments:
2314
2315 package
2316 The name of a Python package. Text-file paths will be
2317 interpreted relative to the directory containing this package.
2318 The package may be supplied as a package object or as a dotted
2319 package name.
2320
2321 setUp
2322 The name of a set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002323 tests in each file. The setUp function will be passed a DocTest
2324 object. The setUp function can access the test globals as the
2325 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002326
2327 tearDown
2328 The name of a tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002329 tests in each file. The tearDown function will be passed a DocTest
2330 object. The tearDown function can access the test globals as the
2331 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002332
2333 globs
2334 A dictionary containing initial global variables for the tests.
Jim Fultonf54bad42004-08-28 14:57:56 +00002335
2336 optionflags
2337 A set of doctest option flags expressed as an integer.
Tim Petersdf7a2082004-08-29 00:38:17 +00002338
Tim Peters19397e52004-08-06 22:02:59 +00002339 """
2340 suite = unittest.TestSuite()
2341
2342 # We do this here so that _normalize_module is called at the right
2343 # level. If it were called in DocFileTest, then this function
2344 # would be the caller and we might guess the package incorrectly.
2345 kw['package'] = _normalize_module(kw.get('package'))
2346
2347 for path in paths:
2348 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002349
Tim Petersdb3756d2003-06-29 05:30:48 +00002350 return suite
2351
Tim Peters8485b562004-08-04 18:46:34 +00002352######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002353## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002354######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002355
Tim Peters19397e52004-08-06 22:02:59 +00002356def script_from_examples(s):
2357 r"""Extract script from text with examples.
2358
2359 Converts text with examples to a Python script. Example input is
2360 converted to regular code. Example output and all other words
2361 are converted to comments:
2362
2363 >>> text = '''
2364 ... Here are examples of simple math.
2365 ...
2366 ... Python has super accurate integer addition
2367 ...
2368 ... >>> 2 + 2
2369 ... 5
2370 ...
2371 ... And very friendly error messages:
2372 ...
2373 ... >>> 1/0
2374 ... To Infinity
2375 ... And
2376 ... Beyond
2377 ...
2378 ... You can use logic if you want:
2379 ...
2380 ... >>> if 0:
2381 ... ... blah
2382 ... ... blah
2383 ... ...
2384 ...
2385 ... Ho hum
2386 ... '''
2387
2388 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002389 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002390 #
Edward Lopera5db6002004-08-12 02:41:30 +00002391 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002392 #
2393 2 + 2
2394 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002395 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002396 #
Edward Lopera5db6002004-08-12 02:41:30 +00002397 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002398 #
2399 1/0
2400 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002401 ## To Infinity
2402 ## And
2403 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002404 #
Edward Lopera5db6002004-08-12 02:41:30 +00002405 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002406 #
2407 if 0:
2408 blah
2409 blah
Tim Peters19397e52004-08-06 22:02:59 +00002410 #
Edward Lopera5db6002004-08-12 02:41:30 +00002411 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002412 """
Edward Loper00f8da72004-08-26 18:05:07 +00002413 output = []
2414 for piece in DocTestParser().parse(s):
2415 if isinstance(piece, Example):
2416 # Add the example's source code (strip trailing NL)
2417 output.append(piece.source[:-1])
2418 # Add the expected output:
2419 want = piece.want
2420 if want:
2421 output.append('# Expected:')
2422 output += ['## '+l for l in want.split('\n')[:-1]]
2423 else:
2424 # Add non-example text.
2425 output += [_comment_line(l)
2426 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002427
Edward Loper00f8da72004-08-26 18:05:07 +00002428 # Trim junk on both ends.
2429 while output and output[-1] == '#':
2430 output.pop()
2431 while output and output[0] == '#':
2432 output.pop(0)
2433 # Combine the output, and return it.
2434 return '\n'.join(output)
Tim Petersdb3756d2003-06-29 05:30:48 +00002435
2436def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002437 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002438
2439 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002440 test to be debugged and the name (within the module) of the object
2441 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002442 """
Tim Peters8485b562004-08-04 18:46:34 +00002443 module = _normalize_module(module)
2444 tests = DocTestFinder().find(module)
2445 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002446 if not test:
2447 raise ValueError(name, "not found in tests")
2448 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002449 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002450 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002451
Jim Fultona643b652004-07-14 19:06:50 +00002452def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002453 """Debug a single doctest docstring, in argument `src`'"""
2454 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002455 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002456
Jim Fultona643b652004-07-14 19:06:50 +00002457def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002458 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002459 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002460
Tim Petersb6a04d62004-08-23 21:37:56 +00002461 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2462 # docs say, a file so created cannot be opened by name a second time
2463 # on modern Windows boxes, and execfile() needs to open it.
2464 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002465 f = open(srcfilename, 'w')
2466 f.write(src)
2467 f.close()
2468
Tim Petersb6a04d62004-08-23 21:37:56 +00002469 try:
2470 if globs:
2471 globs = globs.copy()
2472 else:
2473 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002474
Tim Petersb6a04d62004-08-23 21:37:56 +00002475 if pm:
2476 try:
2477 execfile(srcfilename, globs, globs)
2478 except:
2479 print sys.exc_info()[1]
2480 pdb.post_mortem(sys.exc_info()[2])
2481 else:
2482 # Note that %r is vital here. '%s' instead can, e.g., cause
2483 # backslashes to get treated as metacharacters on Windows.
2484 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2485
2486 finally:
2487 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002488
Jim Fultona643b652004-07-14 19:06:50 +00002489def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002490 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002491
2492 Provide the module (or dotted name of the module) containing the
2493 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002494 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002495 """
Tim Peters8485b562004-08-04 18:46:34 +00002496 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002497 testsrc = testsource(module, name)
2498 debug_script(testsrc, pm, module.__dict__)
2499
Tim Peters8485b562004-08-04 18:46:34 +00002500######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002501## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002502######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002503class _TestClass:
2504 """
2505 A pointless class, for sanity-checking of docstring testing.
2506
2507 Methods:
2508 square()
2509 get()
2510
2511 >>> _TestClass(13).get() + _TestClass(-12).get()
2512 1
2513 >>> hex(_TestClass(13).square().get())
2514 '0xa9'
2515 """
2516
2517 def __init__(self, val):
2518 """val -> _TestClass object with associated value val.
2519
2520 >>> t = _TestClass(123)
2521 >>> print t.get()
2522 123
2523 """
2524
2525 self.val = val
2526
2527 def square(self):
2528 """square() -> square TestClass's associated value
2529
2530 >>> _TestClass(13).square().get()
2531 169
2532 """
2533
2534 self.val = self.val ** 2
2535 return self
2536
2537 def get(self):
2538 """get() -> return TestClass's associated value.
2539
2540 >>> x = _TestClass(-42)
2541 >>> print x.get()
2542 -42
2543 """
2544
2545 return self.val
2546
2547__test__ = {"_TestClass": _TestClass,
2548 "string": r"""
2549 Example of a string object, searched as-is.
2550 >>> x = 1; y = 2
2551 >>> x + y, x * y
2552 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002553 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002554
Tim Peters6ebe61f2003-06-27 20:48:05 +00002555 "bool-int equivalence": r"""
2556 In 2.2, boolean expressions displayed
2557 0 or 1. By default, we still accept
2558 them. This can be disabled by passing
2559 DONT_ACCEPT_TRUE_FOR_1 to the new
2560 optionflags argument.
2561 >>> 4 == 4
2562 1
2563 >>> 4 == 4
2564 True
2565 >>> 4 > 4
2566 0
2567 >>> 4 > 4
2568 False
2569 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002570
Tim Peters8485b562004-08-04 18:46:34 +00002571 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002572 Blank lines can be marked with <BLANKLINE>:
2573 >>> print 'foo\n\nbar\n'
2574 foo
2575 <BLANKLINE>
2576 bar
2577 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002578 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002579
2580 "ellipsis": r"""
2581 If the ellipsis flag is used, then '...' can be used to
2582 elide substrings in the desired output:
2583 >>> print range(1000) #doctest: +ELLIPSIS
2584 [0, 1, 2, ..., 999]
2585 """,
2586
2587 "whitespace normalization": r"""
2588 If the whitespace normalization flag is used, then
2589 differences in whitespace are ignored.
2590 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2591 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2592 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2593 27, 28, 29]
2594 """,
2595 }
Tim Peters8485b562004-08-04 18:46:34 +00002596
Tim Peters8a7d2d52001-01-16 07:10:57 +00002597def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002598 r = unittest.TextTestRunner()
2599 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002600
2601if __name__ == "__main__":
2602 _test()