blob: 3a8496f4401dce4ec31731e890bc1b6187a6e50f [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
Tim Peters82076ef2004-09-13 00:52:51 +00001534 #/////////////////////////////////////////////////////////////////
1535 # Backward compatibility cruft to maintain doctest.master.
1536 #/////////////////////////////////////////////////////////////////
1537 def merge(self, other):
1538 d = self._name2ft
1539 for name, (f, t) in other._name2ft.items():
1540 if name in d:
1541 print "*** DocTestRunner.merge: '" + name + "' in both" \
1542 " testers; summing outcomes."
1543 f2, t2 = d[name]
1544 f = f + f2
1545 t = t + t2
1546 d[name] = f, t
1547
Edward Loper34fcb142004-08-09 02:45:41 +00001548class OutputChecker:
1549 """
1550 A class used to check the whether the actual output from a doctest
1551 example matches the expected output. `OutputChecker` defines two
1552 methods: `check_output`, which compares a given pair of outputs,
1553 and returns true if they match; and `output_difference`, which
1554 returns a string describing the differences between two outputs.
1555 """
1556 def check_output(self, want, got, optionflags):
1557 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001558 Return True iff the actual output from an example (`got`)
1559 matches the expected output (`want`). These strings are
1560 always considered to match if they are identical; but
1561 depending on what option flags the test runner is using,
1562 several non-exact match types are also possible. See the
1563 documentation for `TestRunner` for more information about
1564 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001565 """
1566 # Handle the common case first, for efficiency:
1567 # if they're string-identical, always return true.
1568 if got == want:
1569 return True
1570
1571 # The values True and False replaced 1 and 0 as the return
1572 # value for boolean comparisons in Python 2.3.
1573 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1574 if (got,want) == ("True\n", "1\n"):
1575 return True
1576 if (got,want) == ("False\n", "0\n"):
1577 return True
1578
1579 # <BLANKLINE> can be used as a special sequence to signify a
1580 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1581 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1582 # Replace <BLANKLINE> in want with a blank line.
1583 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1584 '', want)
1585 # If a line in got contains only spaces, then remove the
1586 # spaces.
1587 got = re.sub('(?m)^\s*?$', '', got)
1588 if got == want:
1589 return True
1590
1591 # This flag causes doctest to ignore any differences in the
1592 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001593 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001594 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001595 got = ' '.join(got.split())
1596 want = ' '.join(want.split())
1597 if got == want:
1598 return True
1599
1600 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001601 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001602 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001603 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001604 return True
1605
1606 # We didn't find any match; return false.
1607 return False
1608
Tim Petersc6cbab02004-08-22 19:43:28 +00001609 # Should we do a fancy diff?
1610 def _do_a_fancy_diff(self, want, got, optionflags):
1611 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001612 if not optionflags & (REPORT_UDIFF |
1613 REPORT_CDIFF |
1614 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001615 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001616
Tim Petersc6cbab02004-08-22 19:43:28 +00001617 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001618 # too hard ... or maybe not. In two real-life failures Tim saw,
1619 # a diff was a major help anyway, so this is commented out.
1620 # [todo] _ellipsis_match() knows which pieces do and don't match,
1621 # and could be the basis for a kick-ass diff in this case.
1622 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1623 ## return False
1624
Tim Petersc6cbab02004-08-22 19:43:28 +00001625 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001626 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001627 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001628 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001629
Tim Petersc6cbab02004-08-22 19:43:28 +00001630 # The other diff types need at least a few lines to be helpful.
1631 return want.count('\n') > 2 and got.count('\n') > 2
1632
Edward Loperca9111e2004-08-26 03:00:24 +00001633 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001634 """
1635 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001636 expected output for a given example (`example`) and the actual
1637 output (`got`). `optionflags` is the set of option flags used
1638 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001639 """
Edward Loperca9111e2004-08-26 03:00:24 +00001640 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001641 # If <BLANKLINE>s are being used, then replace blank lines
1642 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001643 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001644 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001645
Tim Peters5b799c12004-08-26 05:21:59 +00001646 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001647 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001648 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001649 want_lines = want.splitlines(True) # True == keep line ends
1650 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001651 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001652 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001653 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1654 diff = list(diff)[2:] # strip the diff header
1655 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001656 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001657 diff = difflib.context_diff(want_lines, got_lines, n=2)
1658 diff = list(diff)[2:] # strip the diff header
1659 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001660 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001661 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1662 diff = list(engine.compare(want_lines, got_lines))
1663 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001664 else:
1665 assert 0, 'Bad diff option'
1666 # Remove trailing whitespace on diff output.
1667 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001668 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001669
1670 # If we're not using diff, then simply list the expected
1671 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001672 if want and got:
1673 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1674 elif want:
1675 return 'Expected:\n%sGot nothing\n' % _indent(want)
1676 elif got:
1677 return 'Expected nothing\nGot:\n%s' % _indent(got)
1678 else:
1679 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001680
Tim Peters19397e52004-08-06 22:02:59 +00001681class DocTestFailure(Exception):
1682 """A DocTest example has failed in debugging mode.
1683
1684 The exception instance has variables:
1685
1686 - test: the DocTest object being run
1687
1688 - excample: the Example object that failed
1689
1690 - got: the actual output
1691 """
1692 def __init__(self, test, example, got):
1693 self.test = test
1694 self.example = example
1695 self.got = got
1696
1697 def __str__(self):
1698 return str(self.test)
1699
1700class UnexpectedException(Exception):
1701 """A DocTest example has encountered an unexpected exception
1702
1703 The exception instance has variables:
1704
1705 - test: the DocTest object being run
1706
1707 - excample: the Example object that failed
1708
1709 - exc_info: the exception info
1710 """
1711 def __init__(self, test, example, exc_info):
1712 self.test = test
1713 self.example = example
1714 self.exc_info = exc_info
1715
1716 def __str__(self):
1717 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001718
Tim Peters19397e52004-08-06 22:02:59 +00001719class DebugRunner(DocTestRunner):
1720 r"""Run doc tests but raise an exception as soon as there is a failure.
1721
1722 If an unexpected exception occurs, an UnexpectedException is raised.
1723 It contains the test, the example, and the original exception:
1724
1725 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001726 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1727 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001728 >>> try:
1729 ... runner.run(test)
1730 ... except UnexpectedException, failure:
1731 ... pass
1732
1733 >>> failure.test is test
1734 True
1735
1736 >>> failure.example.want
1737 '42\n'
1738
1739 >>> exc_info = failure.exc_info
1740 >>> raise exc_info[0], exc_info[1], exc_info[2]
1741 Traceback (most recent call last):
1742 ...
1743 KeyError
1744
1745 We wrap the original exception to give the calling application
1746 access to the test and example information.
1747
1748 If the output doesn't match, then a DocTestFailure is raised:
1749
Edward Lopera1ef6112004-08-09 16:14:41 +00001750 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001751 ... >>> x = 1
1752 ... >>> x
1753 ... 2
1754 ... ''', {}, 'foo', 'foo.py', 0)
1755
1756 >>> try:
1757 ... runner.run(test)
1758 ... except DocTestFailure, failure:
1759 ... pass
1760
1761 DocTestFailure objects provide access to the test:
1762
1763 >>> failure.test is test
1764 True
1765
1766 As well as to the example:
1767
1768 >>> failure.example.want
1769 '2\n'
1770
1771 and the actual output:
1772
1773 >>> failure.got
1774 '1\n'
1775
1776 If a failure or error occurs, the globals are left intact:
1777
1778 >>> del test.globs['__builtins__']
1779 >>> test.globs
1780 {'x': 1}
1781
Edward Lopera1ef6112004-08-09 16:14:41 +00001782 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001783 ... >>> x = 2
1784 ... >>> raise KeyError
1785 ... ''', {}, 'foo', 'foo.py', 0)
1786
1787 >>> runner.run(test)
1788 Traceback (most recent call last):
1789 ...
1790 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001791
Tim Peters19397e52004-08-06 22:02:59 +00001792 >>> del test.globs['__builtins__']
1793 >>> test.globs
1794 {'x': 2}
1795
1796 But the globals are cleared if there is no error:
1797
Edward Lopera1ef6112004-08-09 16:14:41 +00001798 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001799 ... >>> x = 2
1800 ... ''', {}, 'foo', 'foo.py', 0)
1801
1802 >>> runner.run(test)
1803 (0, 1)
1804
1805 >>> test.globs
1806 {}
1807
1808 """
1809
1810 def run(self, test, compileflags=None, out=None, clear_globs=True):
1811 r = DocTestRunner.run(self, test, compileflags, out, False)
1812 if clear_globs:
1813 test.globs.clear()
1814 return r
1815
1816 def report_unexpected_exception(self, out, test, example, exc_info):
1817 raise UnexpectedException(test, example, exc_info)
1818
1819 def report_failure(self, out, test, example, got):
1820 raise DocTestFailure(test, example, got)
1821
Tim Peters8485b562004-08-04 18:46:34 +00001822######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001823## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001824######################################################################
1825# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001826
Tim Peters82076ef2004-09-13 00:52:51 +00001827# For backward compatibility, a global instance of a DocTestRunner
1828# class, updated by testmod.
1829master = None
1830
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001831def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001832 report=True, optionflags=0, extraglobs=None,
1833 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001834 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001835 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001836
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001837 Test examples in docstrings in functions and classes reachable
1838 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001839 with m.__doc__. Unless isprivate is specified, private names
1840 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001841
1842 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001843 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001844 function and class docstrings are tested even if the name is private;
1845 strings are tested directly, as if they were docstrings.
1846
1847 Return (#failures, #tests).
1848
1849 See doctest.__doc__ for an overview.
1850
1851 Optional keyword arg "name" gives the name of the module; by default
1852 use m.__name__.
1853
1854 Optional keyword arg "globs" gives a dict to be used as the globals
1855 when executing examples; by default, use m.__dict__. A copy of this
1856 dict is actually used for each docstring, so that each docstring's
1857 examples start with a clean slate.
1858
Tim Peters8485b562004-08-04 18:46:34 +00001859 Optional keyword arg "extraglobs" gives a dictionary that should be
1860 merged into the globals that are used to execute examples. By
1861 default, no extra globals are used. This is new in 2.4.
1862
Tim Peters8a7d2d52001-01-16 07:10:57 +00001863 Optional keyword arg "verbose" prints lots of stuff if true, prints
1864 only failures if false; by default, it's true iff "-v" is in sys.argv.
1865
Tim Peters8a7d2d52001-01-16 07:10:57 +00001866 Optional keyword arg "report" prints a summary at the end when true,
1867 else prints nothing at the end. In verbose mode, the summary is
1868 detailed, else very brief (in fact, empty if all tests passed).
1869
Tim Peters6ebe61f2003-06-27 20:48:05 +00001870 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001871 and defaults to 0. This is new in 2.3. Possible values (see the
1872 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001873
1874 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001875 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001876 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001877 ELLIPSIS
Edward Loper71f55af2004-08-26 01:41:51 +00001878 REPORT_UDIFF
1879 REPORT_CDIFF
1880 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001881 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001882
1883 Optional keyword arg "raise_on_error" raises an exception on the
1884 first unexpected exception or failure. This allows failures to be
1885 post-mortem debugged.
1886
Tim Petersf727c6c2004-08-08 01:48:59 +00001887 Deprecated in Python 2.4:
1888 Optional keyword arg "isprivate" specifies a function used to
1889 determine whether a name is private. The default function is
1890 treat all functions as public. Optionally, "isprivate" can be
1891 set to doctest.is_private to skip over functions marked as private
1892 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001893 """
1894
1895 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001896 Advanced tomfoolery: testmod runs methods of a local instance of
1897 class doctest.Tester, then merges the results into (or creates)
1898 global Tester instance doctest.master. Methods of doctest.master
1899 can be called directly too, if you want to do something unusual.
1900 Passing report=0 to testmod is especially useful then, to delay
1901 displaying a summary. Invoke doctest.master.summarize(verbose)
1902 when you're done fiddling.
1903 """
Tim Peters82076ef2004-09-13 00:52:51 +00001904 global master
1905
Tim Petersf727c6c2004-08-08 01:48:59 +00001906 if isprivate is not None:
1907 warnings.warn("the isprivate argument is deprecated; "
1908 "examine DocTestFinder.find() lists instead",
1909 DeprecationWarning)
1910
Tim Peters8485b562004-08-04 18:46:34 +00001911 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001912 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001913 # DWA - m will still be None if this wasn't invoked from the command
1914 # line, in which case the following TypeError is about as good an error
1915 # as we should expect
1916 m = sys.modules.get('__main__')
1917
Tim Peters8485b562004-08-04 18:46:34 +00001918 # Check that we were actually given a module.
1919 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001920 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001921
1922 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001923 if name is None:
1924 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001925
1926 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001927 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001928
1929 if raise_on_error:
1930 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1931 else:
1932 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1933
Tim Peters8485b562004-08-04 18:46:34 +00001934 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1935 runner.run(test)
1936
Tim Peters8a7d2d52001-01-16 07:10:57 +00001937 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001938 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001939
Tim Peters82076ef2004-09-13 00:52:51 +00001940 if master is None:
1941 master = runner
1942 else:
1943 master.merge(runner)
1944
Tim Peters8485b562004-08-04 18:46:34 +00001945 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001946
Tim Peters8485b562004-08-04 18:46:34 +00001947def run_docstring_examples(f, globs, verbose=False, name="NoName",
1948 compileflags=None, optionflags=0):
1949 """
1950 Test examples in the given object's docstring (`f`), using `globs`
1951 as globals. Optional argument `name` is used in failure messages.
1952 If the optional argument `verbose` is true, then generate output
1953 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001954
Tim Peters8485b562004-08-04 18:46:34 +00001955 `compileflags` gives the set of flags that should be used by the
1956 Python compiler when running the examples. If not specified, then
1957 it will default to the set of future-import flags that apply to
1958 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001959
Tim Peters8485b562004-08-04 18:46:34 +00001960 Optional keyword arg `optionflags` specifies options for the
1961 testing and output. See the documentation for `testmod` for more
1962 information.
1963 """
1964 # Find, parse, and run all tests in the given module.
1965 finder = DocTestFinder(verbose=verbose, recurse=False)
1966 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1967 for test in finder.find(f, name, globs=globs):
1968 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001969
Tim Peters8485b562004-08-04 18:46:34 +00001970######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001971## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001972######################################################################
1973# This is provided only for backwards compatibility. It's not
1974# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001975
Tim Peters8485b562004-08-04 18:46:34 +00001976class Tester:
1977 def __init__(self, mod=None, globs=None, verbose=None,
1978 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001979
1980 warnings.warn("class Tester is deprecated; "
1981 "use class doctest.DocTestRunner instead",
1982 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001983 if mod is None and globs is None:
1984 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters4be7a922004-09-12 22:39:46 +00001985 if mod is not None and not inspect.ismodule(mod):
Tim Peters8485b562004-08-04 18:46:34 +00001986 raise TypeError("Tester.__init__: mod must be a module; %r" %
1987 (mod,))
1988 if globs is None:
1989 globs = mod.__dict__
1990 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001991
Tim Peters8485b562004-08-04 18:46:34 +00001992 self.verbose = verbose
1993 self.isprivate = isprivate
1994 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001995 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001996 self.testrunner = DocTestRunner(verbose=verbose,
1997 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001998
Tim Peters8485b562004-08-04 18:46:34 +00001999 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00002000 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00002001 if self.verbose:
2002 print "Running string", name
2003 (f,t) = self.testrunner.run(test)
2004 if self.verbose:
2005 print f, "of", t, "examples failed in string", name
2006 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002007
Tim Petersf3f57472004-08-08 06:11:48 +00002008 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00002009 f = t = 0
2010 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00002011 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00002012 for test in tests:
2013 (f2, t2) = self.testrunner.run(test)
2014 (f,t) = (f+f2, t+t2)
2015 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002016
Tim Peters8485b562004-08-04 18:46:34 +00002017 def rundict(self, d, name, module=None):
2018 import new
2019 m = new.module(name)
2020 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00002021 if module is None:
2022 module = False
2023 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00002024
Tim Peters8485b562004-08-04 18:46:34 +00002025 def run__test__(self, d, name):
2026 import new
2027 m = new.module(name)
2028 m.__test__ = d
Tim Peters9661f9a2004-09-12 22:45:17 +00002029 return self.rundoc(m, name)
Tim Petersdb3756d2003-06-29 05:30:48 +00002030
Tim Peters8485b562004-08-04 18:46:34 +00002031 def summarize(self, verbose=None):
2032 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00002033
Tim Peters8485b562004-08-04 18:46:34 +00002034 def merge(self, other):
Tim Peters82076ef2004-09-13 00:52:51 +00002035 self.testrunner.merge(other.testrunner)
Tim Petersdb3756d2003-06-29 05:30:48 +00002036
Tim Peters8485b562004-08-04 18:46:34 +00002037######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002038## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002039######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002040
Jim Fultonf54bad42004-08-28 14:57:56 +00002041_unittest_reportflags = 0
Tim Peters38330fe2004-08-30 16:19:24 +00002042
Jim Fultonf54bad42004-08-28 14:57:56 +00002043def set_unittest_reportflags(flags):
Tim Peters38330fe2004-08-30 16:19:24 +00002044 """Sets the unittest option flags.
Jim Fultonf54bad42004-08-28 14:57:56 +00002045
2046 The old flag is returned so that a runner could restore the old
2047 value if it wished to:
2048
2049 >>> old = _unittest_reportflags
2050 >>> set_unittest_reportflags(REPORT_NDIFF |
2051 ... REPORT_ONLY_FIRST_FAILURE) == old
2052 True
2053
2054 >>> import doctest
2055 >>> doctest._unittest_reportflags == (REPORT_NDIFF |
2056 ... REPORT_ONLY_FIRST_FAILURE)
2057 True
Tim Petersdf7a2082004-08-29 00:38:17 +00002058
Jim Fultonf54bad42004-08-28 14:57:56 +00002059 Only reporting flags can be set:
2060
2061 >>> set_unittest_reportflags(ELLIPSIS)
2062 Traceback (most recent call last):
2063 ...
Tim Peters38330fe2004-08-30 16:19:24 +00002064 ValueError: ('Only reporting flags allowed', 8)
Jim Fultonf54bad42004-08-28 14:57:56 +00002065
2066 >>> set_unittest_reportflags(old) == (REPORT_NDIFF |
2067 ... REPORT_ONLY_FIRST_FAILURE)
2068 True
Jim Fultonf54bad42004-08-28 14:57:56 +00002069 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002070 global _unittest_reportflags
Tim Peters38330fe2004-08-30 16:19:24 +00002071
2072 if (flags & REPORTING_FLAGS) != flags:
2073 raise ValueError("Only reporting flags allowed", flags)
Jim Fultonf54bad42004-08-28 14:57:56 +00002074 old = _unittest_reportflags
2075 _unittest_reportflags = flags
2076 return old
Tim Petersdf7a2082004-08-29 00:38:17 +00002077
Jim Fultonf54bad42004-08-28 14:57:56 +00002078
Tim Peters19397e52004-08-06 22:02:59 +00002079class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002080
Edward Loper34fcb142004-08-09 02:45:41 +00002081 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2082 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002083
Jim Fultona643b652004-07-14 19:06:50 +00002084 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002085 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002086 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002087 self._dt_test = test
2088 self._dt_setUp = setUp
2089 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002090
Jim Fultona643b652004-07-14 19:06:50 +00002091 def setUp(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002092 test = self._dt_test
Tim Petersdf7a2082004-08-29 00:38:17 +00002093
Tim Peters19397e52004-08-06 22:02:59 +00002094 if self._dt_setUp is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002095 self._dt_setUp(test)
Jim Fultona643b652004-07-14 19:06:50 +00002096
2097 def tearDown(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002098 test = self._dt_test
2099
Tim Peters19397e52004-08-06 22:02:59 +00002100 if self._dt_tearDown is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002101 self._dt_tearDown(test)
2102
2103 test.globs.clear()
Jim Fultona643b652004-07-14 19:06:50 +00002104
2105 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002106 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002107 old = sys.stdout
2108 new = StringIO()
Jim Fultonf54bad42004-08-28 14:57:56 +00002109 optionflags = self._dt_optionflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002110
Tim Peters38330fe2004-08-30 16:19:24 +00002111 if not (optionflags & REPORTING_FLAGS):
Jim Fultonf54bad42004-08-28 14:57:56 +00002112 # The option flags don't include any reporting flags,
2113 # so add the default reporting flags
2114 optionflags |= _unittest_reportflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002115
Jim Fultonf54bad42004-08-28 14:57:56 +00002116 runner = DocTestRunner(optionflags=optionflags,
Edward Loper34fcb142004-08-09 02:45:41 +00002117 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002118
Jim Fultona643b652004-07-14 19:06:50 +00002119 try:
Tim Peters19397e52004-08-06 22:02:59 +00002120 runner.DIVIDER = "-"*70
Jim Fultonf54bad42004-08-28 14:57:56 +00002121 failures, tries = runner.run(
2122 test, out=new.write, clear_globs=False)
Jim Fultona643b652004-07-14 19:06:50 +00002123 finally:
2124 sys.stdout = old
2125
2126 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002127 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002128
Tim Peters19397e52004-08-06 22:02:59 +00002129 def format_failure(self, err):
2130 test = self._dt_test
2131 if test.lineno is None:
2132 lineno = 'unknown line number'
2133 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002134 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002135 lname = '.'.join(test.name.split('.')[-1:])
2136 return ('Failed doctest test for %s\n'
2137 ' File "%s", line %s, in %s\n\n%s'
2138 % (test.name, test.filename, lineno, lname, err)
2139 )
2140
2141 def debug(self):
2142 r"""Run the test case without results and without catching exceptions
2143
2144 The unit test framework includes a debug method on test cases
2145 and test suites to support post-mortem debugging. The test code
2146 is run in such a way that errors are not caught. This way a
2147 caller can catch the errors and initiate post-mortem debugging.
2148
2149 The DocTestCase provides a debug method that raises
2150 UnexpectedException errors if there is an unexepcted
2151 exception:
2152
Edward Lopera1ef6112004-08-09 16:14:41 +00002153 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002154 ... {}, 'foo', 'foo.py', 0)
2155 >>> case = DocTestCase(test)
2156 >>> try:
2157 ... case.debug()
2158 ... except UnexpectedException, failure:
2159 ... pass
2160
2161 The UnexpectedException contains the test, the example, and
2162 the original exception:
2163
2164 >>> failure.test is test
2165 True
2166
2167 >>> failure.example.want
2168 '42\n'
2169
2170 >>> exc_info = failure.exc_info
2171 >>> raise exc_info[0], exc_info[1], exc_info[2]
2172 Traceback (most recent call last):
2173 ...
2174 KeyError
2175
2176 If the output doesn't match, then a DocTestFailure is raised:
2177
Edward Lopera1ef6112004-08-09 16:14:41 +00002178 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002179 ... >>> x = 1
2180 ... >>> x
2181 ... 2
2182 ... ''', {}, 'foo', 'foo.py', 0)
2183 >>> case = DocTestCase(test)
2184
2185 >>> try:
2186 ... case.debug()
2187 ... except DocTestFailure, failure:
2188 ... pass
2189
2190 DocTestFailure objects provide access to the test:
2191
2192 >>> failure.test is test
2193 True
2194
2195 As well as to the example:
2196
2197 >>> failure.example.want
2198 '2\n'
2199
2200 and the actual output:
2201
2202 >>> failure.got
2203 '1\n'
2204
2205 """
2206
Jim Fultonf54bad42004-08-28 14:57:56 +00002207 self.setUp()
Edward Loper34fcb142004-08-09 02:45:41 +00002208 runner = DebugRunner(optionflags=self._dt_optionflags,
2209 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002210 runner.run(self._dt_test)
Jim Fultonf54bad42004-08-28 14:57:56 +00002211 self.tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002212
2213 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002214 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002215
2216 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002217 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002218 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2219
2220 __str__ = __repr__
2221
2222 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002223 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002224
Jim Fultonf54bad42004-08-28 14:57:56 +00002225def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2226 **options):
Tim Peters8485b562004-08-04 18:46:34 +00002227 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002228 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002229
Tim Peters19397e52004-08-06 22:02:59 +00002230 This converts each documentation string in a module that
2231 contains doctest tests to a unittest test case. If any of the
2232 tests in a doc string fail, then the test case fails. An exception
2233 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002234 (sometimes approximate) line number.
2235
Tim Peters19397e52004-08-06 22:02:59 +00002236 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002237 can be either a module or a module name.
2238
2239 If no argument is given, the calling module is used.
Jim Fultonf54bad42004-08-28 14:57:56 +00002240
2241 A number of options may be provided as keyword arguments:
2242
2243 package
2244 The name of a Python package. Text-file paths will be
2245 interpreted relative to the directory containing this package.
2246 The package may be supplied as a package object or as a dotted
2247 package name.
2248
2249 setUp
2250 The name of a set-up function. This is called before running the
2251 tests in each file. The setUp function will be passed a DocTest
2252 object. The setUp function can access the test globals as the
2253 globs attribute of the test passed.
2254
2255 tearDown
2256 The name of a tear-down function. This is called after running the
2257 tests in each file. The tearDown function will be passed a DocTest
2258 object. The tearDown function can access the test globals as the
2259 globs attribute of the test passed.
2260
2261 globs
2262 A dictionary containing initial global variables for the tests.
2263
2264 optionflags
2265 A set of doctest option flags expressed as an integer.
Jim Fultona643b652004-07-14 19:06:50 +00002266 """
Jim Fultona643b652004-07-14 19:06:50 +00002267
Tim Peters8485b562004-08-04 18:46:34 +00002268 if test_finder is None:
2269 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002270
Tim Peters19397e52004-08-06 22:02:59 +00002271 module = _normalize_module(module)
2272 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2273 if globs is None:
2274 globs = module.__dict__
Jim Fultonf54bad42004-08-28 14:57:56 +00002275 if not tests:
2276 # Why do we want to do this? Because it reveals a bug that might
2277 # otherwise be hidden.
Tim Peters19397e52004-08-06 22:02:59 +00002278 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002279
2280 tests.sort()
2281 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002282 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002283 if len(test.examples) == 0:
2284 continue
Tim Peters8485b562004-08-04 18:46:34 +00002285 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002286 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002287 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002288 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002289 test.filename = filename
Jim Fultonf54bad42004-08-28 14:57:56 +00002290 suite.addTest(DocTestCase(test, **options))
Tim Peters19397e52004-08-06 22:02:59 +00002291
2292 return suite
2293
2294class DocFileCase(DocTestCase):
2295
2296 def id(self):
2297 return '_'.join(self._dt_test.name.split('.'))
2298
2299 def __repr__(self):
2300 return self._dt_test.filename
2301 __str__ = __repr__
2302
2303 def format_failure(self, err):
2304 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2305 % (self._dt_test.name, self._dt_test.filename, err)
2306 )
2307
Jim Fultonf54bad42004-08-28 14:57:56 +00002308def DocFileTest(path, package=None, globs=None, **options):
Tim Peters19397e52004-08-06 22:02:59 +00002309 package = _normalize_module(package)
2310 name = path.split('/')[-1]
2311 dir = os.path.split(package.__file__)[0]
2312 path = os.path.join(dir, *(path.split('/')))
2313 doc = open(path).read()
2314
2315 if globs is None:
2316 globs = {}
2317
Edward Lopera1ef6112004-08-09 16:14:41 +00002318 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002319
Jim Fultonf54bad42004-08-28 14:57:56 +00002320 return DocFileCase(test, **options)
Tim Peters19397e52004-08-06 22:02:59 +00002321
2322def DocFileSuite(*paths, **kw):
2323 """Creates a suite of doctest files.
2324
2325 One or more text file paths are given as strings. These should
2326 use "/" characters to separate path segments. Paths are relative
2327 to the directory of the calling module, or relative to the package
2328 passed as a keyword argument.
2329
2330 A number of options may be provided as keyword arguments:
2331
2332 package
2333 The name of a Python package. Text-file paths will be
2334 interpreted relative to the directory containing this package.
2335 The package may be supplied as a package object or as a dotted
2336 package name.
2337
2338 setUp
2339 The name of a set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002340 tests in each file. The setUp function will be passed a DocTest
2341 object. The setUp function can access the test globals as the
2342 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002343
2344 tearDown
2345 The name of a tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002346 tests in each file. The tearDown function will be passed a DocTest
2347 object. The tearDown function can access the test globals as the
2348 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002349
2350 globs
2351 A dictionary containing initial global variables for the tests.
Jim Fultonf54bad42004-08-28 14:57:56 +00002352
2353 optionflags
2354 A set of doctest option flags expressed as an integer.
Tim Petersdf7a2082004-08-29 00:38:17 +00002355
Tim Peters19397e52004-08-06 22:02:59 +00002356 """
2357 suite = unittest.TestSuite()
2358
2359 # We do this here so that _normalize_module is called at the right
2360 # level. If it were called in DocFileTest, then this function
2361 # would be the caller and we might guess the package incorrectly.
2362 kw['package'] = _normalize_module(kw.get('package'))
2363
2364 for path in paths:
2365 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002366
Tim Petersdb3756d2003-06-29 05:30:48 +00002367 return suite
2368
Tim Peters8485b562004-08-04 18:46:34 +00002369######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002370## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002371######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002372
Tim Peters19397e52004-08-06 22:02:59 +00002373def script_from_examples(s):
2374 r"""Extract script from text with examples.
2375
2376 Converts text with examples to a Python script. Example input is
2377 converted to regular code. Example output and all other words
2378 are converted to comments:
2379
2380 >>> text = '''
2381 ... Here are examples of simple math.
2382 ...
2383 ... Python has super accurate integer addition
2384 ...
2385 ... >>> 2 + 2
2386 ... 5
2387 ...
2388 ... And very friendly error messages:
2389 ...
2390 ... >>> 1/0
2391 ... To Infinity
2392 ... And
2393 ... Beyond
2394 ...
2395 ... You can use logic if you want:
2396 ...
2397 ... >>> if 0:
2398 ... ... blah
2399 ... ... blah
2400 ... ...
2401 ...
2402 ... Ho hum
2403 ... '''
2404
2405 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002406 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002407 #
Edward Lopera5db6002004-08-12 02:41:30 +00002408 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002409 #
2410 2 + 2
2411 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002412 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002413 #
Edward Lopera5db6002004-08-12 02:41:30 +00002414 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002415 #
2416 1/0
2417 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002418 ## To Infinity
2419 ## And
2420 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002421 #
Edward Lopera5db6002004-08-12 02:41:30 +00002422 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002423 #
2424 if 0:
2425 blah
2426 blah
Tim Peters19397e52004-08-06 22:02:59 +00002427 #
Edward Lopera5db6002004-08-12 02:41:30 +00002428 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002429 """
Edward Loper00f8da72004-08-26 18:05:07 +00002430 output = []
2431 for piece in DocTestParser().parse(s):
2432 if isinstance(piece, Example):
2433 # Add the example's source code (strip trailing NL)
2434 output.append(piece.source[:-1])
2435 # Add the expected output:
2436 want = piece.want
2437 if want:
2438 output.append('# Expected:')
2439 output += ['## '+l for l in want.split('\n')[:-1]]
2440 else:
2441 # Add non-example text.
2442 output += [_comment_line(l)
2443 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002444
Edward Loper00f8da72004-08-26 18:05:07 +00002445 # Trim junk on both ends.
2446 while output and output[-1] == '#':
2447 output.pop()
2448 while output and output[0] == '#':
2449 output.pop(0)
2450 # Combine the output, and return it.
2451 return '\n'.join(output)
Tim Petersdb3756d2003-06-29 05:30:48 +00002452
2453def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002454 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002455
2456 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002457 test to be debugged and the name (within the module) of the object
2458 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002459 """
Tim Peters8485b562004-08-04 18:46:34 +00002460 module = _normalize_module(module)
2461 tests = DocTestFinder().find(module)
2462 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002463 if not test:
2464 raise ValueError(name, "not found in tests")
2465 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002466 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002467 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002468
Jim Fultona643b652004-07-14 19:06:50 +00002469def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002470 """Debug a single doctest docstring, in argument `src`'"""
2471 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002472 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002473
Jim Fultona643b652004-07-14 19:06:50 +00002474def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002475 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002476 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002477
Tim Petersb6a04d62004-08-23 21:37:56 +00002478 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2479 # docs say, a file so created cannot be opened by name a second time
2480 # on modern Windows boxes, and execfile() needs to open it.
2481 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002482 f = open(srcfilename, 'w')
2483 f.write(src)
2484 f.close()
2485
Tim Petersb6a04d62004-08-23 21:37:56 +00002486 try:
2487 if globs:
2488 globs = globs.copy()
2489 else:
2490 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002491
Tim Petersb6a04d62004-08-23 21:37:56 +00002492 if pm:
2493 try:
2494 execfile(srcfilename, globs, globs)
2495 except:
2496 print sys.exc_info()[1]
2497 pdb.post_mortem(sys.exc_info()[2])
2498 else:
2499 # Note that %r is vital here. '%s' instead can, e.g., cause
2500 # backslashes to get treated as metacharacters on Windows.
2501 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2502
2503 finally:
2504 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002505
Jim Fultona643b652004-07-14 19:06:50 +00002506def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002507 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002508
2509 Provide the module (or dotted name of the module) containing the
2510 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002511 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002512 """
Tim Peters8485b562004-08-04 18:46:34 +00002513 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002514 testsrc = testsource(module, name)
2515 debug_script(testsrc, pm, module.__dict__)
2516
Tim Peters8485b562004-08-04 18:46:34 +00002517######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002518## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002519######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002520class _TestClass:
2521 """
2522 A pointless class, for sanity-checking of docstring testing.
2523
2524 Methods:
2525 square()
2526 get()
2527
2528 >>> _TestClass(13).get() + _TestClass(-12).get()
2529 1
2530 >>> hex(_TestClass(13).square().get())
2531 '0xa9'
2532 """
2533
2534 def __init__(self, val):
2535 """val -> _TestClass object with associated value val.
2536
2537 >>> t = _TestClass(123)
2538 >>> print t.get()
2539 123
2540 """
2541
2542 self.val = val
2543
2544 def square(self):
2545 """square() -> square TestClass's associated value
2546
2547 >>> _TestClass(13).square().get()
2548 169
2549 """
2550
2551 self.val = self.val ** 2
2552 return self
2553
2554 def get(self):
2555 """get() -> return TestClass's associated value.
2556
2557 >>> x = _TestClass(-42)
2558 >>> print x.get()
2559 -42
2560 """
2561
2562 return self.val
2563
2564__test__ = {"_TestClass": _TestClass,
2565 "string": r"""
2566 Example of a string object, searched as-is.
2567 >>> x = 1; y = 2
2568 >>> x + y, x * y
2569 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002570 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002571
Tim Peters6ebe61f2003-06-27 20:48:05 +00002572 "bool-int equivalence": r"""
2573 In 2.2, boolean expressions displayed
2574 0 or 1. By default, we still accept
2575 them. This can be disabled by passing
2576 DONT_ACCEPT_TRUE_FOR_1 to the new
2577 optionflags argument.
2578 >>> 4 == 4
2579 1
2580 >>> 4 == 4
2581 True
2582 >>> 4 > 4
2583 0
2584 >>> 4 > 4
2585 False
2586 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002587
Tim Peters8485b562004-08-04 18:46:34 +00002588 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002589 Blank lines can be marked with <BLANKLINE>:
2590 >>> print 'foo\n\nbar\n'
2591 foo
2592 <BLANKLINE>
2593 bar
2594 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002595 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002596
2597 "ellipsis": r"""
2598 If the ellipsis flag is used, then '...' can be used to
2599 elide substrings in the desired output:
2600 >>> print range(1000) #doctest: +ELLIPSIS
2601 [0, 1, 2, ..., 999]
2602 """,
2603
2604 "whitespace normalization": r"""
2605 If the whitespace normalization flag is used, then
2606 differences in whitespace are ignored.
2607 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2608 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2609 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2610 27, 28, 29]
2611 """,
2612 }
Tim Peters8485b562004-08-04 18:46:34 +00002613
Tim Peters8a7d2d52001-01-16 07:10:57 +00002614def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002615 r = unittest.TextTestRunner()
2616 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002617
2618if __name__ == "__main__":
2619 _test()