blob: c1a87b38811c3dbf56a1150fe02de5945ab34ffd [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 Peters958cc892004-09-13 14:53:28 +0000851 recurse=True, _namefilter=None, exclude_empty=True):
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.
Edward Loper32ddbf72004-09-13 05:47:24 +0000863
Tim Peters958cc892004-09-13 14:53:28 +0000864 If the optional argument `exclude_empty` is false, then `find`
865 will include tests for objects with empty docstrings.
Tim Peters8485b562004-08-04 18:46:34 +0000866 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000867 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000868 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000869 self._recurse = recurse
Edward Loper32ddbf72004-09-13 05:47:24 +0000870 self._exclude_empty = exclude_empty
Tim Petersf727c6c2004-08-08 01:48:59 +0000871 # _namefilter is undocumented, and exists only for temporary backward-
872 # compatibility support of testmod's deprecated isprivate mess.
873 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000874
875 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000876 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000877 """
878 Return a list of the DocTests that are defined by the given
879 object's docstring, or by any of its contained objects'
880 docstrings.
881
882 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000883 the given object. If the module is not specified or is None, then
884 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000885 correct module. The object's module is used:
886
887 - As a default namespace, if `globs` is not specified.
888 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000889 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000890 - To find the name of the file containing the object.
891 - To help find the line number of the object within its
892 file.
893
Tim Petersf3f57472004-08-08 06:11:48 +0000894 Contained objects whose module does not match `module` are ignored.
895
896 If `module` is False, no attempt to find the module will be made.
897 This is obscure, of use mostly in tests: if `module` is False, or
898 is None but cannot be found automatically, then all objects are
899 considered to belong to the (non-existent) module, so all contained
900 objects will (recursively) be searched for doctests.
901
Tim Peters8485b562004-08-04 18:46:34 +0000902 The globals for each DocTest is formed by combining `globs`
903 and `extraglobs` (bindings in `extraglobs` override bindings
904 in `globs`). A new copy of the globals dictionary is created
905 for each DocTest. If `globs` is not specified, then it
906 defaults to the module's `__dict__`, if specified, or {}
907 otherwise. If `extraglobs` is not specified, then it defaults
908 to {}.
909
Tim Peters8485b562004-08-04 18:46:34 +0000910 """
911 # If name was not specified, then extract it from the object.
912 if name is None:
913 name = getattr(obj, '__name__', None)
914 if name is None:
915 raise ValueError("DocTestFinder.find: name must be given "
916 "when obj.__name__ doesn't exist: %r" %
917 (type(obj),))
918
919 # Find the module that contains the given object (if obj is
920 # a module, then module=obj.). Note: this may fail, in which
921 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000922 if module is False:
923 module = None
924 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000925 module = inspect.getmodule(obj)
926
927 # Read the module's source code. This is used by
928 # DocTestFinder._find_lineno to find the line number for a
929 # given object's docstring.
930 try:
931 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
932 source_lines = linecache.getlines(file)
933 if not source_lines:
934 source_lines = None
935 except TypeError:
936 source_lines = None
937
938 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000939 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000940 if module is None:
941 globs = {}
942 else:
943 globs = module.__dict__.copy()
944 else:
945 globs = globs.copy()
946 if extraglobs is not None:
947 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000948
Tim Peters8485b562004-08-04 18:46:34 +0000949 # Recursively expore `obj`, extracting DocTests.
950 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000951 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000952 return tests
953
954 def _filter(self, obj, prefix, base):
955 """
956 Return true if the given object should not be examined.
957 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000958 return (self._namefilter is not None and
959 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000960
961 def _from_module(self, module, object):
962 """
963 Return true if the given object is defined in the given
964 module.
965 """
966 if module is None:
967 return True
968 elif inspect.isfunction(object):
969 return module.__dict__ is object.func_globals
970 elif inspect.isclass(object):
971 return module.__name__ == object.__module__
972 elif inspect.getmodule(object) is not None:
973 return module is inspect.getmodule(object)
974 elif hasattr(object, '__module__'):
975 return module.__name__ == object.__module__
976 elif isinstance(object, property):
977 return True # [XX] no way not be sure.
978 else:
979 raise ValueError("object must be a class or function")
980
Tim Petersf3f57472004-08-08 06:11:48 +0000981 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000982 """
983 Find tests for the given object and any contained objects, and
984 add them to `tests`.
985 """
986 if self._verbose:
987 print 'Finding tests in %s' % name
988
989 # If we've already processed this object, then ignore it.
990 if id(obj) in seen:
991 return
992 seen[id(obj)] = 1
993
994 # Find a test for this object, and add it to the list of tests.
995 test = self._get_test(obj, name, module, globs, source_lines)
996 if test is not None:
997 tests.append(test)
998
999 # Look for tests in a module's contained objects.
1000 if inspect.ismodule(obj) and self._recurse:
1001 for valname, val in obj.__dict__.items():
1002 # Check if this contained object should be ignored.
1003 if self._filter(val, name, valname):
1004 continue
1005 valname = '%s.%s' % (name, valname)
1006 # Recurse to functions & classes.
1007 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +00001008 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001009 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001010 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001011
1012 # Look for tests in a module's __test__ dictionary.
1013 if inspect.ismodule(obj) and self._recurse:
1014 for valname, val in getattr(obj, '__test__', {}).items():
1015 if not isinstance(valname, basestring):
1016 raise ValueError("DocTestFinder.find: __test__ keys "
1017 "must be strings: %r" %
1018 (type(valname),))
1019 if not (inspect.isfunction(val) or inspect.isclass(val) or
1020 inspect.ismethod(val) or inspect.ismodule(val) or
1021 isinstance(val, basestring)):
1022 raise ValueError("DocTestFinder.find: __test__ values "
1023 "must be strings, functions, methods, "
1024 "classes, or modules: %r" %
1025 (type(val),))
Tim Petersc5684782004-09-13 01:07:12 +00001026 valname = '%s.__test__.%s' % (name, valname)
Tim Peters8485b562004-08-04 18:46:34 +00001027 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001028 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001029
1030 # Look for tests in a class's contained objects.
1031 if inspect.isclass(obj) and self._recurse:
1032 for valname, val in obj.__dict__.items():
1033 # Check if this contained object should be ignored.
1034 if self._filter(val, name, valname):
1035 continue
1036 # Special handling for staticmethod/classmethod.
1037 if isinstance(val, staticmethod):
1038 val = getattr(obj, valname)
1039 if isinstance(val, classmethod):
1040 val = getattr(obj, valname).im_func
1041
1042 # Recurse to methods, properties, and nested classes.
1043 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001044 isinstance(val, property)) and
1045 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001046 valname = '%s.%s' % (name, valname)
1047 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001048 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001049
1050 def _get_test(self, obj, name, module, globs, source_lines):
1051 """
1052 Return a DocTest for the given object, if it defines a docstring;
1053 otherwise, return None.
1054 """
1055 # Extract the object's docstring. If it doesn't have one,
1056 # then return None (no test for this object).
1057 if isinstance(obj, basestring):
1058 docstring = obj
1059 else:
1060 try:
1061 if obj.__doc__ is None:
Edward Loper32ddbf72004-09-13 05:47:24 +00001062 docstring = ''
1063 else:
1064 docstring = str(obj.__doc__)
Tim Peters8485b562004-08-04 18:46:34 +00001065 except (TypeError, AttributeError):
Edward Loper32ddbf72004-09-13 05:47:24 +00001066 docstring = ''
Tim Peters8485b562004-08-04 18:46:34 +00001067
1068 # Find the docstring's location in the file.
1069 lineno = self._find_lineno(obj, source_lines)
1070
Edward Loper32ddbf72004-09-13 05:47:24 +00001071 # Don't bother if the docstring is empty.
1072 if self._exclude_empty and not docstring:
1073 return None
1074
Tim Peters8485b562004-08-04 18:46:34 +00001075 # Return a DocTest for this object.
1076 if module is None:
1077 filename = None
1078 else:
1079 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001080 if filename[-4:] in (".pyc", ".pyo"):
1081 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001082 return self._parser.get_doctest(docstring, globs, name,
1083 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001084
1085 def _find_lineno(self, obj, source_lines):
1086 """
1087 Return a line number of the given object's docstring. Note:
1088 this method assumes that the object has a docstring.
1089 """
1090 lineno = None
1091
1092 # Find the line number for modules.
1093 if inspect.ismodule(obj):
1094 lineno = 0
1095
1096 # Find the line number for classes.
1097 # Note: this could be fooled if a class is defined multiple
1098 # times in a single file.
1099 if inspect.isclass(obj):
1100 if source_lines is None:
1101 return None
1102 pat = re.compile(r'^\s*class\s*%s\b' %
1103 getattr(obj, '__name__', '-'))
1104 for i, line in enumerate(source_lines):
1105 if pat.match(line):
1106 lineno = i
1107 break
1108
1109 # Find the line number for functions & methods.
1110 if inspect.ismethod(obj): obj = obj.im_func
1111 if inspect.isfunction(obj): obj = obj.func_code
1112 if inspect.istraceback(obj): obj = obj.tb_frame
1113 if inspect.isframe(obj): obj = obj.f_code
1114 if inspect.iscode(obj):
1115 lineno = getattr(obj, 'co_firstlineno', None)-1
1116
1117 # Find the line number where the docstring starts. Assume
1118 # that it's the first line that begins with a quote mark.
1119 # Note: this could be fooled by a multiline function
1120 # signature, where a continuation line begins with a quote
1121 # mark.
1122 if lineno is not None:
1123 if source_lines is None:
1124 return lineno+1
1125 pat = re.compile('(^|.*:)\s*\w*("|\')')
1126 for lineno in range(lineno, len(source_lines)):
1127 if pat.match(source_lines[lineno]):
1128 return lineno
1129
1130 # We couldn't find the line number.
1131 return None
1132
1133######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001134## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001135######################################################################
1136
Tim Peters8485b562004-08-04 18:46:34 +00001137class DocTestRunner:
1138 """
1139 A class used to run DocTest test cases, and accumulate statistics.
1140 The `run` method is used to process a single DocTest case. It
1141 returns a tuple `(f, t)`, where `t` is the number of test cases
1142 tried, and `f` is the number of test cases that failed.
1143
1144 >>> tests = DocTestFinder().find(_TestClass)
1145 >>> runner = DocTestRunner(verbose=False)
1146 >>> for test in tests:
1147 ... print runner.run(test)
1148 (0, 2)
1149 (0, 1)
1150 (0, 2)
1151 (0, 2)
1152
1153 The `summarize` method prints a summary of all the test cases that
1154 have been run by the runner, and returns an aggregated `(f, t)`
1155 tuple:
1156
1157 >>> runner.summarize(verbose=1)
1158 4 items passed all tests:
1159 2 tests in _TestClass
1160 2 tests in _TestClass.__init__
1161 2 tests in _TestClass.get
1162 1 tests in _TestClass.square
1163 7 tests in 4 items.
1164 7 passed and 0 failed.
1165 Test passed.
1166 (0, 7)
1167
1168 The aggregated number of tried examples and failed examples is
1169 also available via the `tries` and `failures` attributes:
1170
1171 >>> runner.tries
1172 7
1173 >>> runner.failures
1174 0
1175
1176 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001177 by an `OutputChecker`. This comparison may be customized with a
1178 number of option flags; see the documentation for `testmod` for
1179 more information. If the option flags are insufficient, then the
1180 comparison may also be customized by passing a subclass of
1181 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001182
1183 The test runner's display output can be controlled in two ways.
1184 First, an output function (`out) can be passed to
1185 `TestRunner.run`; this function will be called with strings that
1186 should be displayed. It defaults to `sys.stdout.write`. If
1187 capturing the output is not sufficient, then the display output
1188 can be also customized by subclassing DocTestRunner, and
1189 overriding the methods `report_start`, `report_success`,
1190 `report_unexpected_exception`, and `report_failure`.
1191 """
1192 # This divider string is used to separate failure messages, and to
1193 # separate sections of the summary.
1194 DIVIDER = "*" * 70
1195
Edward Loper34fcb142004-08-09 02:45:41 +00001196 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001197 """
1198 Create a new test runner.
1199
Edward Loper34fcb142004-08-09 02:45:41 +00001200 Optional keyword arg `checker` is the `OutputChecker` that
1201 should be used to compare the expected outputs and actual
1202 outputs of doctest examples.
1203
Tim Peters8485b562004-08-04 18:46:34 +00001204 Optional keyword arg 'verbose' prints lots of stuff if true,
1205 only failures if false; by default, it's true iff '-v' is in
1206 sys.argv.
1207
1208 Optional argument `optionflags` can be used to control how the
1209 test runner compares expected output to actual output, and how
1210 it displays failures. See the documentation for `testmod` for
1211 more information.
1212 """
Edward Loper34fcb142004-08-09 02:45:41 +00001213 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001214 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001215 verbose = '-v' in sys.argv
1216 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001217 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001218 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001219
Tim Peters8485b562004-08-04 18:46:34 +00001220 # Keep track of the examples we've run.
1221 self.tries = 0
1222 self.failures = 0
1223 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001224
Tim Peters8485b562004-08-04 18:46:34 +00001225 # Create a fake output target for capturing doctest output.
1226 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001227
Tim Peters8485b562004-08-04 18:46:34 +00001228 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001229 # Reporting methods
1230 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001231
Tim Peters8485b562004-08-04 18:46:34 +00001232 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001233 """
Tim Peters8485b562004-08-04 18:46:34 +00001234 Report that the test runner is about to process the given
1235 example. (Only displays a message if verbose=True)
1236 """
1237 if self._verbose:
Edward Loperaacf0832004-08-26 01:19:50 +00001238 if example.want:
1239 out('Trying:\n' + _indent(example.source) +
1240 'Expecting:\n' + _indent(example.want))
1241 else:
1242 out('Trying:\n' + _indent(example.source) +
1243 'Expecting nothing\n')
Tim Peters8a7d2d52001-01-16 07:10:57 +00001244
Tim Peters8485b562004-08-04 18:46:34 +00001245 def report_success(self, out, test, example, got):
1246 """
1247 Report that the given example ran successfully. (Only
1248 displays a message if verbose=True)
1249 """
1250 if self._verbose:
1251 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001252
Tim Peters8485b562004-08-04 18:46:34 +00001253 def report_failure(self, out, test, example, got):
1254 """
1255 Report that the given example failed.
1256 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001257 out(self._failure_header(test, example) +
Edward Loperca9111e2004-08-26 03:00:24 +00001258 self._checker.output_difference(example, got, self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001259
Tim Peters8485b562004-08-04 18:46:34 +00001260 def report_unexpected_exception(self, out, test, example, exc_info):
1261 """
1262 Report that the given example raised an unexpected exception.
1263 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001264 out(self._failure_header(test, example) +
Edward Loperaacf0832004-08-26 01:19:50 +00001265 'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001266
Edward Loper8e4a34b2004-08-12 02:34:27 +00001267 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001268 out = [self.DIVIDER]
1269 if test.filename:
1270 if test.lineno is not None and example.lineno is not None:
1271 lineno = test.lineno + example.lineno + 1
1272 else:
1273 lineno = '?'
1274 out.append('File "%s", line %s, in %s' %
1275 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001276 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001277 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1278 out.append('Failed example:')
1279 source = example.source
Edward Loperaacf0832004-08-26 01:19:50 +00001280 out.append(_indent(source))
1281 return '\n'.join(out)
Tim Peters7402f792001-10-02 03:53:41 +00001282
Tim Peters8485b562004-08-04 18:46:34 +00001283 #/////////////////////////////////////////////////////////////////
1284 # DocTest Running
1285 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001286
Tim Peters8485b562004-08-04 18:46:34 +00001287 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001288 """
Tim Peters8485b562004-08-04 18:46:34 +00001289 Run the examples in `test`. Write the outcome of each example
1290 with one of the `DocTestRunner.report_*` methods, using the
1291 writer function `out`. `compileflags` is the set of compiler
1292 flags that should be used to execute examples. Return a tuple
1293 `(f, t)`, where `t` is the number of examples tried, and `f`
1294 is the number of examples that failed. The examples are run
1295 in the namespace `test.globs`.
1296 """
1297 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001298 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001299
1300 # Save the option flags (since option directives can be used
1301 # to modify them).
1302 original_optionflags = self.optionflags
1303
Tim Peters1fbf9c52004-09-04 17:21:02 +00001304 SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
1305
1306 check = self._checker.check_output
1307
Tim Peters8485b562004-08-04 18:46:34 +00001308 # Process each example.
Edward Loper2de91ba2004-08-27 02:07:46 +00001309 for examplenum, example in enumerate(test.examples):
1310
Edward Lopera89f88d2004-08-26 02:45:51 +00001311 # If REPORT_ONLY_FIRST_FAILURE is set, then supress
1312 # reporting after the first failure.
1313 quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
1314 failures > 0)
1315
Edward Loper74bca7a2004-08-12 02:27:44 +00001316 # Merge in the example's options.
1317 self.optionflags = original_optionflags
1318 if example.options:
1319 for (optionflag, val) in example.options.items():
1320 if val:
1321 self.optionflags |= optionflag
1322 else:
1323 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001324
1325 # Record that we started this example.
1326 tries += 1
Edward Lopera89f88d2004-08-26 02:45:51 +00001327 if not quiet:
1328 self.report_start(out, test, example)
Tim Peters8485b562004-08-04 18:46:34 +00001329
Edward Loper2de91ba2004-08-27 02:07:46 +00001330 # Use a special filename for compile(), so we can retrieve
1331 # the source code during interactive debugging (see
1332 # __patched_linecache_getlines).
1333 filename = '<doctest %s[%d]>' % (test.name, examplenum)
1334
Tim Peters8485b562004-08-04 18:46:34 +00001335 # Run the example in the given context (globs), and record
1336 # any exception that gets raised. (But don't intercept
1337 # keyboard interrupts.)
1338 try:
Tim Peters208ca702004-08-09 04:12:36 +00001339 # Don't blink! This is where the user's code gets run.
Edward Loper2de91ba2004-08-27 02:07:46 +00001340 exec compile(example.source, filename, "single",
Tim Peters8485b562004-08-04 18:46:34 +00001341 compileflags, 1) in test.globs
Edward Loper2de91ba2004-08-27 02:07:46 +00001342 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001343 exception = None
1344 except KeyboardInterrupt:
1345 raise
1346 except:
1347 exception = sys.exc_info()
Edward Loper2de91ba2004-08-27 02:07:46 +00001348 self.debugger.set_continue() # ==== Example Finished ====
Tim Peters8485b562004-08-04 18:46:34 +00001349
Tim Peters208ca702004-08-09 04:12:36 +00001350 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001351 self._fakeout.truncate(0)
Tim Peters1fbf9c52004-09-04 17:21:02 +00001352 outcome = FAILURE # guilty until proved innocent or insane
Tim Peters8485b562004-08-04 18:46:34 +00001353
1354 # If the example executed without raising any exceptions,
Tim Peters1fbf9c52004-09-04 17:21:02 +00001355 # verify its output.
Tim Peters8485b562004-08-04 18:46:34 +00001356 if exception is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001357 if check(example.want, got, self.optionflags):
1358 outcome = SUCCESS
Tim Peters8485b562004-08-04 18:46:34 +00001359
Tim Peters1fbf9c52004-09-04 17:21:02 +00001360 # The example raised an exception: check if it was expected.
Tim Peters8485b562004-08-04 18:46:34 +00001361 else:
1362 exc_info = sys.exc_info()
1363 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
Tim Peters1fbf9c52004-09-04 17:21:02 +00001364 if not quiet:
1365 got += _exception_traceback(exc_info)
Tim Peters8485b562004-08-04 18:46:34 +00001366
Tim Peters1fbf9c52004-09-04 17:21:02 +00001367 # If `example.exc_msg` is None, then we weren't expecting
1368 # an exception.
Edward Lopera6b68322004-08-26 00:05:43 +00001369 if example.exc_msg is None:
Tim Peters1fbf9c52004-09-04 17:21:02 +00001370 outcome = BOOM
1371
1372 # We expected an exception: see whether it matches.
1373 elif check(example.exc_msg, exc_msg, self.optionflags):
1374 outcome = SUCCESS
1375
1376 # Another chance if they didn't care about the detail.
1377 elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
1378 m1 = re.match(r'[^:]*:', example.exc_msg)
1379 m2 = re.match(r'[^:]*:', exc_msg)
1380 if m1 and m2 and check(m1.group(0), m2.group(0),
1381 self.optionflags):
1382 outcome = SUCCESS
1383
1384 # Report the outcome.
1385 if outcome is SUCCESS:
1386 if not quiet:
1387 self.report_success(out, test, example, got)
1388 elif outcome is FAILURE:
1389 if not quiet:
1390 self.report_failure(out, test, example, got)
1391 failures += 1
1392 elif outcome is BOOM:
1393 if not quiet:
1394 self.report_unexpected_exception(out, test, example,
1395 exc_info)
1396 failures += 1
1397 else:
1398 assert False, ("unknown outcome", outcome)
Tim Peters8485b562004-08-04 18:46:34 +00001399
1400 # Restore the option flags (in case they were modified)
1401 self.optionflags = original_optionflags
1402
1403 # Record and return the number of failures and tries.
1404 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001405 return failures, tries
1406
Tim Peters8485b562004-08-04 18:46:34 +00001407 def __record_outcome(self, test, f, t):
1408 """
1409 Record the fact that the given DocTest (`test`) generated `f`
1410 failures out of `t` tried examples.
1411 """
1412 f2, t2 = self._name2ft.get(test.name, (0,0))
1413 self._name2ft[test.name] = (f+f2, t+t2)
1414 self.failures += f
1415 self.tries += t
1416
Edward Loper2de91ba2004-08-27 02:07:46 +00001417 __LINECACHE_FILENAME_RE = re.compile(r'<doctest '
1418 r'(?P<name>[\w\.]+)'
1419 r'\[(?P<examplenum>\d+)\]>$')
1420 def __patched_linecache_getlines(self, filename):
1421 m = self.__LINECACHE_FILENAME_RE.match(filename)
1422 if m and m.group('name') == self.test.name:
1423 example = self.test.examples[int(m.group('examplenum'))]
1424 return example.source.splitlines(True)
1425 else:
1426 return self.save_linecache_getlines(filename)
1427
Tim Peters8485b562004-08-04 18:46:34 +00001428 def run(self, test, compileflags=None, out=None, clear_globs=True):
1429 """
1430 Run the examples in `test`, and display the results using the
1431 writer function `out`.
1432
1433 The examples are run in the namespace `test.globs`. If
1434 `clear_globs` is true (the default), then this namespace will
1435 be cleared after the test runs, to help with garbage
1436 collection. If you would like to examine the namespace after
1437 the test completes, then use `clear_globs=False`.
1438
1439 `compileflags` gives the set of flags that should be used by
1440 the Python compiler when running the examples. If not
1441 specified, then it will default to the set of future-import
1442 flags that apply to `globs`.
1443
1444 The output of each example is checked using
1445 `DocTestRunner.check_output`, and the results are formatted by
1446 the `DocTestRunner.report_*` methods.
1447 """
Edward Loper2de91ba2004-08-27 02:07:46 +00001448 self.test = test
1449
Tim Peters8485b562004-08-04 18:46:34 +00001450 if compileflags is None:
1451 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001452
Tim Peters6c542b72004-08-09 16:43:36 +00001453 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001454 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001455 out = save_stdout.write
1456 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001457
Edward Loper2de91ba2004-08-27 02:07:46 +00001458 # Patch pdb.set_trace to restore sys.stdout during interactive
1459 # debugging (so it's not still redirected to self._fakeout).
1460 # Note that the interactive output will go to *our*
1461 # save_stdout, even if that's not the real sys.stdout; this
1462 # allows us to write test cases for the set_trace behavior.
Tim Peters6c542b72004-08-09 16:43:36 +00001463 save_set_trace = pdb.set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001464 self.debugger = _OutputRedirectingPdb(save_stdout)
1465 self.debugger.reset()
1466 pdb.set_trace = self.debugger.set_trace
1467
1468 # Patch linecache.getlines, so we can see the example's source
1469 # when we're inside the debugger.
1470 self.save_linecache_getlines = linecache.getlines
1471 linecache.getlines = self.__patched_linecache_getlines
1472
Tim Peters8485b562004-08-04 18:46:34 +00001473 try:
Tim Peters8485b562004-08-04 18:46:34 +00001474 return self.__run(test, compileflags, out)
1475 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001476 sys.stdout = save_stdout
1477 pdb.set_trace = save_set_trace
Edward Loper2de91ba2004-08-27 02:07:46 +00001478 linecache.getlines = self.save_linecache_getlines
Tim Peters8485b562004-08-04 18:46:34 +00001479 if clear_globs:
1480 test.globs.clear()
1481
1482 #/////////////////////////////////////////////////////////////////
1483 # Summarization
1484 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001485 def summarize(self, verbose=None):
1486 """
Tim Peters8485b562004-08-04 18:46:34 +00001487 Print a summary of all the test cases that have been run by
1488 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1489 the total number of failed examples, and `t` is the total
1490 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001491
Tim Peters8485b562004-08-04 18:46:34 +00001492 The optional `verbose` argument controls how detailed the
1493 summary is. If the verbosity is not specified, then the
1494 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001495 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001496 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001497 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001498 notests = []
1499 passed = []
1500 failed = []
1501 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001502 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001503 name, (f, t) = x
1504 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001505 totalt += t
1506 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001507 if t == 0:
1508 notests.append(name)
1509 elif f == 0:
1510 passed.append( (name, t) )
1511 else:
1512 failed.append(x)
1513 if verbose:
1514 if notests:
1515 print len(notests), "items had no tests:"
1516 notests.sort()
1517 for thing in notests:
1518 print " ", thing
1519 if passed:
1520 print len(passed), "items passed all tests:"
1521 passed.sort()
1522 for thing, count in passed:
1523 print " %3d tests in %s" % (count, thing)
1524 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001525 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001526 print len(failed), "items had failures:"
1527 failed.sort()
1528 for thing, (f, t) in failed:
1529 print " %3d of %3d in %s" % (f, t, thing)
1530 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001531 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001532 print totalt - totalf, "passed and", totalf, "failed."
1533 if totalf:
1534 print "***Test Failed***", totalf, "failures."
1535 elif verbose:
1536 print "Test passed."
1537 return totalf, totalt
1538
Tim Peters82076ef2004-09-13 00:52:51 +00001539 #/////////////////////////////////////////////////////////////////
1540 # Backward compatibility cruft to maintain doctest.master.
1541 #/////////////////////////////////////////////////////////////////
1542 def merge(self, other):
1543 d = self._name2ft
1544 for name, (f, t) in other._name2ft.items():
1545 if name in d:
1546 print "*** DocTestRunner.merge: '" + name + "' in both" \
1547 " testers; summing outcomes."
1548 f2, t2 = d[name]
1549 f = f + f2
1550 t = t + t2
1551 d[name] = f, t
1552
Edward Loper34fcb142004-08-09 02:45:41 +00001553class OutputChecker:
1554 """
1555 A class used to check the whether the actual output from a doctest
1556 example matches the expected output. `OutputChecker` defines two
1557 methods: `check_output`, which compares a given pair of outputs,
1558 and returns true if they match; and `output_difference`, which
1559 returns a string describing the differences between two outputs.
1560 """
1561 def check_output(self, want, got, optionflags):
1562 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001563 Return True iff the actual output from an example (`got`)
1564 matches the expected output (`want`). These strings are
1565 always considered to match if they are identical; but
1566 depending on what option flags the test runner is using,
1567 several non-exact match types are also possible. See the
1568 documentation for `TestRunner` for more information about
1569 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001570 """
1571 # Handle the common case first, for efficiency:
1572 # if they're string-identical, always return true.
1573 if got == want:
1574 return True
1575
1576 # The values True and False replaced 1 and 0 as the return
1577 # value for boolean comparisons in Python 2.3.
1578 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1579 if (got,want) == ("True\n", "1\n"):
1580 return True
1581 if (got,want) == ("False\n", "0\n"):
1582 return True
1583
1584 # <BLANKLINE> can be used as a special sequence to signify a
1585 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1586 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1587 # Replace <BLANKLINE> in want with a blank line.
1588 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1589 '', want)
1590 # If a line in got contains only spaces, then remove the
1591 # spaces.
1592 got = re.sub('(?m)^\s*?$', '', got)
1593 if got == want:
1594 return True
1595
1596 # This flag causes doctest to ignore any differences in the
1597 # contents of whitespace strings. Note that this can be used
Tim Peters3fa8c202004-08-23 21:43:39 +00001598 # in conjunction with the ELLIPSIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001599 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001600 got = ' '.join(got.split())
1601 want = ' '.join(want.split())
1602 if got == want:
1603 return True
1604
1605 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001606 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001607 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001608 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001609 return True
1610
1611 # We didn't find any match; return false.
1612 return False
1613
Tim Petersc6cbab02004-08-22 19:43:28 +00001614 # Should we do a fancy diff?
1615 def _do_a_fancy_diff(self, want, got, optionflags):
1616 # Not unless they asked for a fancy diff.
Edward Loper71f55af2004-08-26 01:41:51 +00001617 if not optionflags & (REPORT_UDIFF |
1618 REPORT_CDIFF |
1619 REPORT_NDIFF):
Tim Petersc6cbab02004-08-22 19:43:28 +00001620 return False
Tim Peters5b799c12004-08-26 05:21:59 +00001621
Tim Petersc6cbab02004-08-22 19:43:28 +00001622 # If expected output uses ellipsis, a meaningful fancy diff is
Tim Peters5b799c12004-08-26 05:21:59 +00001623 # too hard ... or maybe not. In two real-life failures Tim saw,
1624 # a diff was a major help anyway, so this is commented out.
1625 # [todo] _ellipsis_match() knows which pieces do and don't match,
1626 # and could be the basis for a kick-ass diff in this case.
1627 ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
1628 ## return False
1629
Tim Petersc6cbab02004-08-22 19:43:28 +00001630 # ndiff does intraline difference marking, so can be useful even
Tim Peters5b799c12004-08-26 05:21:59 +00001631 # for 1-line differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001632 if optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001633 return True
Tim Peters5b799c12004-08-26 05:21:59 +00001634
Tim Petersc6cbab02004-08-22 19:43:28 +00001635 # The other diff types need at least a few lines to be helpful.
1636 return want.count('\n') > 2 and got.count('\n') > 2
1637
Edward Loperca9111e2004-08-26 03:00:24 +00001638 def output_difference(self, example, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001639 """
1640 Return a string describing the differences between the
Edward Loperca9111e2004-08-26 03:00:24 +00001641 expected output for a given example (`example`) and the actual
1642 output (`got`). `optionflags` is the set of option flags used
1643 to compare `want` and `got`.
Edward Loper34fcb142004-08-09 02:45:41 +00001644 """
Edward Loperca9111e2004-08-26 03:00:24 +00001645 want = example.want
Edward Loper68ba9a62004-08-12 02:43:49 +00001646 # If <BLANKLINE>s are being used, then replace blank lines
1647 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001648 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001649 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001650
Tim Peters5b799c12004-08-26 05:21:59 +00001651 # Check if we should use diff.
Tim Petersc6cbab02004-08-22 19:43:28 +00001652 if self._do_a_fancy_diff(want, got, optionflags):
Edward Loper34fcb142004-08-09 02:45:41 +00001653 # Split want & got into lines.
Tim Peterse7edcb82004-08-26 05:44:27 +00001654 want_lines = want.splitlines(True) # True == keep line ends
1655 got_lines = got.splitlines(True)
Edward Loper34fcb142004-08-09 02:45:41 +00001656 # Use difflib to find their differences.
Edward Loper71f55af2004-08-26 01:41:51 +00001657 if optionflags & REPORT_UDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001658 diff = difflib.unified_diff(want_lines, got_lines, n=2)
1659 diff = list(diff)[2:] # strip the diff header
1660 kind = 'unified diff with -expected +actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001661 elif optionflags & REPORT_CDIFF:
Edward Loper56629292004-08-26 01:31:56 +00001662 diff = difflib.context_diff(want_lines, got_lines, n=2)
1663 diff = list(diff)[2:] # strip the diff header
1664 kind = 'context diff with expected followed by actual'
Edward Loper71f55af2004-08-26 01:41:51 +00001665 elif optionflags & REPORT_NDIFF:
Tim Petersc6cbab02004-08-22 19:43:28 +00001666 engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
1667 diff = list(engine.compare(want_lines, got_lines))
1668 kind = 'ndiff with -expected +actual'
Edward Loper34fcb142004-08-09 02:45:41 +00001669 else:
1670 assert 0, 'Bad diff option'
1671 # Remove trailing whitespace on diff output.
1672 diff = [line.rstrip() + '\n' for line in diff]
Edward Loperaacf0832004-08-26 01:19:50 +00001673 return 'Differences (%s):\n' % kind + _indent(''.join(diff))
Edward Loper34fcb142004-08-09 02:45:41 +00001674
1675 # If we're not using diff, then simply list the expected
1676 # output followed by the actual output.
Edward Loperaacf0832004-08-26 01:19:50 +00001677 if want and got:
1678 return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
1679 elif want:
1680 return 'Expected:\n%sGot nothing\n' % _indent(want)
1681 elif got:
1682 return 'Expected nothing\nGot:\n%s' % _indent(got)
1683 else:
1684 return 'Expected nothing\nGot nothing\n'
Edward Loper34fcb142004-08-09 02:45:41 +00001685
Tim Peters19397e52004-08-06 22:02:59 +00001686class DocTestFailure(Exception):
1687 """A DocTest example has failed in debugging mode.
1688
1689 The exception instance has variables:
1690
1691 - test: the DocTest object being run
1692
1693 - excample: the Example object that failed
1694
1695 - got: the actual output
1696 """
1697 def __init__(self, test, example, got):
1698 self.test = test
1699 self.example = example
1700 self.got = got
1701
1702 def __str__(self):
1703 return str(self.test)
1704
1705class UnexpectedException(Exception):
1706 """A DocTest example has encountered an unexpected exception
1707
1708 The exception instance has variables:
1709
1710 - test: the DocTest object being run
1711
1712 - excample: the Example object that failed
1713
1714 - exc_info: the exception info
1715 """
1716 def __init__(self, test, example, exc_info):
1717 self.test = test
1718 self.example = example
1719 self.exc_info = exc_info
1720
1721 def __str__(self):
1722 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001723
Tim Peters19397e52004-08-06 22:02:59 +00001724class DebugRunner(DocTestRunner):
1725 r"""Run doc tests but raise an exception as soon as there is a failure.
1726
1727 If an unexpected exception occurs, an UnexpectedException is raised.
1728 It contains the test, the example, and the original exception:
1729
1730 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001731 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1732 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001733 >>> try:
1734 ... runner.run(test)
1735 ... except UnexpectedException, failure:
1736 ... pass
1737
1738 >>> failure.test is test
1739 True
1740
1741 >>> failure.example.want
1742 '42\n'
1743
1744 >>> exc_info = failure.exc_info
1745 >>> raise exc_info[0], exc_info[1], exc_info[2]
1746 Traceback (most recent call last):
1747 ...
1748 KeyError
1749
1750 We wrap the original exception to give the calling application
1751 access to the test and example information.
1752
1753 If the output doesn't match, then a DocTestFailure is raised:
1754
Edward Lopera1ef6112004-08-09 16:14:41 +00001755 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001756 ... >>> x = 1
1757 ... >>> x
1758 ... 2
1759 ... ''', {}, 'foo', 'foo.py', 0)
1760
1761 >>> try:
1762 ... runner.run(test)
1763 ... except DocTestFailure, failure:
1764 ... pass
1765
1766 DocTestFailure objects provide access to the test:
1767
1768 >>> failure.test is test
1769 True
1770
1771 As well as to the example:
1772
1773 >>> failure.example.want
1774 '2\n'
1775
1776 and the actual output:
1777
1778 >>> failure.got
1779 '1\n'
1780
1781 If a failure or error occurs, the globals are left intact:
1782
1783 >>> del test.globs['__builtins__']
1784 >>> test.globs
1785 {'x': 1}
1786
Edward Lopera1ef6112004-08-09 16:14:41 +00001787 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001788 ... >>> x = 2
1789 ... >>> raise KeyError
1790 ... ''', {}, 'foo', 'foo.py', 0)
1791
1792 >>> runner.run(test)
1793 Traceback (most recent call last):
1794 ...
1795 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001796
Tim Peters19397e52004-08-06 22:02:59 +00001797 >>> del test.globs['__builtins__']
1798 >>> test.globs
1799 {'x': 2}
1800
1801 But the globals are cleared if there is no error:
1802
Edward Lopera1ef6112004-08-09 16:14:41 +00001803 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001804 ... >>> x = 2
1805 ... ''', {}, 'foo', 'foo.py', 0)
1806
1807 >>> runner.run(test)
1808 (0, 1)
1809
1810 >>> test.globs
1811 {}
1812
1813 """
1814
1815 def run(self, test, compileflags=None, out=None, clear_globs=True):
1816 r = DocTestRunner.run(self, test, compileflags, out, False)
1817 if clear_globs:
1818 test.globs.clear()
1819 return r
1820
1821 def report_unexpected_exception(self, out, test, example, exc_info):
1822 raise UnexpectedException(test, example, exc_info)
1823
1824 def report_failure(self, out, test, example, got):
1825 raise DocTestFailure(test, example, got)
1826
Tim Peters8485b562004-08-04 18:46:34 +00001827######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001828## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001829######################################################################
1830# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001831
Tim Peters82076ef2004-09-13 00:52:51 +00001832# For backward compatibility, a global instance of a DocTestRunner
1833# class, updated by testmod.
1834master = None
1835
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001836def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001837 report=True, optionflags=0, extraglobs=None,
Tim Peters958cc892004-09-13 14:53:28 +00001838 raise_on_error=False, exclude_empty=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001839 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters958cc892004-09-13 14:53:28 +00001840 report=True, optionflags=0, extraglobs=None, raise_on_error=False,
1841 exclude_empty=False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001842
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001843 Test examples in docstrings in functions and classes reachable
1844 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001845 with m.__doc__. Unless isprivate is specified, private names
1846 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001847
1848 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001849 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001850 function and class docstrings are tested even if the name is private;
1851 strings are tested directly, as if they were docstrings.
1852
1853 Return (#failures, #tests).
1854
1855 See doctest.__doc__ for an overview.
1856
1857 Optional keyword arg "name" gives the name of the module; by default
1858 use m.__name__.
1859
1860 Optional keyword arg "globs" gives a dict to be used as the globals
1861 when executing examples; by default, use m.__dict__. A copy of this
1862 dict is actually used for each docstring, so that each docstring's
1863 examples start with a clean slate.
1864
Tim Peters8485b562004-08-04 18:46:34 +00001865 Optional keyword arg "extraglobs" gives a dictionary that should be
1866 merged into the globals that are used to execute examples. By
1867 default, no extra globals are used. This is new in 2.4.
1868
Tim Peters8a7d2d52001-01-16 07:10:57 +00001869 Optional keyword arg "verbose" prints lots of stuff if true, prints
1870 only failures if false; by default, it's true iff "-v" is in sys.argv.
1871
Tim Peters8a7d2d52001-01-16 07:10:57 +00001872 Optional keyword arg "report" prints a summary at the end when true,
1873 else prints nothing at the end. In verbose mode, the summary is
1874 detailed, else very brief (in fact, empty if all tests passed).
1875
Tim Peters6ebe61f2003-06-27 20:48:05 +00001876 Optional keyword arg "optionflags" or's together module constants,
Tim Petersf82a9de2004-08-22 20:51:53 +00001877 and defaults to 0. This is new in 2.3. Possible values (see the
1878 docs for details):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001879
1880 DONT_ACCEPT_TRUE_FOR_1
Tim Peters8485b562004-08-04 18:46:34 +00001881 DONT_ACCEPT_BLANKLINE
Tim Peters8485b562004-08-04 18:46:34 +00001882 NORMALIZE_WHITESPACE
Tim Peters8485b562004-08-04 18:46:34 +00001883 ELLIPSIS
Edward Loper71f55af2004-08-26 01:41:51 +00001884 REPORT_UDIFF
1885 REPORT_CDIFF
1886 REPORT_NDIFF
Edward Lopera89f88d2004-08-26 02:45:51 +00001887 REPORT_ONLY_FIRST_FAILURE
Tim Peters19397e52004-08-06 22:02:59 +00001888
1889 Optional keyword arg "raise_on_error" raises an exception on the
1890 first unexpected exception or failure. This allows failures to be
1891 post-mortem debugged.
1892
Tim Petersf727c6c2004-08-08 01:48:59 +00001893 Deprecated in Python 2.4:
1894 Optional keyword arg "isprivate" specifies a function used to
1895 determine whether a name is private. The default function is
1896 treat all functions as public. Optionally, "isprivate" can be
1897 set to doctest.is_private to skip over functions marked as private
1898 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001899 """
1900
1901 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001902 Advanced tomfoolery: testmod runs methods of a local instance of
1903 class doctest.Tester, then merges the results into (or creates)
1904 global Tester instance doctest.master. Methods of doctest.master
1905 can be called directly too, if you want to do something unusual.
1906 Passing report=0 to testmod is especially useful then, to delay
1907 displaying a summary. Invoke doctest.master.summarize(verbose)
1908 when you're done fiddling.
1909 """
Tim Peters82076ef2004-09-13 00:52:51 +00001910 global master
1911
Tim Petersf727c6c2004-08-08 01:48:59 +00001912 if isprivate is not None:
1913 warnings.warn("the isprivate argument is deprecated; "
1914 "examine DocTestFinder.find() lists instead",
1915 DeprecationWarning)
1916
Tim Peters8485b562004-08-04 18:46:34 +00001917 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001918 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001919 # DWA - m will still be None if this wasn't invoked from the command
1920 # line, in which case the following TypeError is about as good an error
1921 # as we should expect
1922 m = sys.modules.get('__main__')
1923
Tim Peters8485b562004-08-04 18:46:34 +00001924 # Check that we were actually given a module.
1925 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001926 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001927
1928 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001929 if name is None:
1930 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001931
1932 # Find, parse, and run all tests in the given module.
Tim Peters958cc892004-09-13 14:53:28 +00001933 finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty)
Tim Peters19397e52004-08-06 22:02:59 +00001934
1935 if raise_on_error:
1936 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1937 else:
1938 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1939
Tim Peters8485b562004-08-04 18:46:34 +00001940 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1941 runner.run(test)
1942
Tim Peters8a7d2d52001-01-16 07:10:57 +00001943 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001944 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001945
Tim Peters82076ef2004-09-13 00:52:51 +00001946 if master is None:
1947 master = runner
1948 else:
1949 master.merge(runner)
1950
Tim Peters8485b562004-08-04 18:46:34 +00001951 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001952
Tim Peters8485b562004-08-04 18:46:34 +00001953def run_docstring_examples(f, globs, verbose=False, name="NoName",
1954 compileflags=None, optionflags=0):
1955 """
1956 Test examples in the given object's docstring (`f`), using `globs`
1957 as globals. Optional argument `name` is used in failure messages.
1958 If the optional argument `verbose` is true, then generate output
1959 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001960
Tim Peters8485b562004-08-04 18:46:34 +00001961 `compileflags` gives the set of flags that should be used by the
1962 Python compiler when running the examples. If not specified, then
1963 it will default to the set of future-import flags that apply to
1964 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001965
Tim Peters8485b562004-08-04 18:46:34 +00001966 Optional keyword arg `optionflags` specifies options for the
1967 testing and output. See the documentation for `testmod` for more
1968 information.
1969 """
1970 # Find, parse, and run all tests in the given module.
1971 finder = DocTestFinder(verbose=verbose, recurse=False)
1972 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1973 for test in finder.find(f, name, globs=globs):
1974 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001975
Tim Peters8485b562004-08-04 18:46:34 +00001976######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001977## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001978######################################################################
1979# This is provided only for backwards compatibility. It's not
1980# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001981
Tim Peters8485b562004-08-04 18:46:34 +00001982class Tester:
1983 def __init__(self, mod=None, globs=None, verbose=None,
1984 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001985
1986 warnings.warn("class Tester is deprecated; "
1987 "use class doctest.DocTestRunner instead",
1988 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001989 if mod is None and globs is None:
1990 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters4be7a922004-09-12 22:39:46 +00001991 if mod is not None and not inspect.ismodule(mod):
Tim Peters8485b562004-08-04 18:46:34 +00001992 raise TypeError("Tester.__init__: mod must be a module; %r" %
1993 (mod,))
1994 if globs is None:
1995 globs = mod.__dict__
1996 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001997
Tim Peters8485b562004-08-04 18:46:34 +00001998 self.verbose = verbose
1999 self.isprivate = isprivate
2000 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00002001 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00002002 self.testrunner = DocTestRunner(verbose=verbose,
2003 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00002004
Tim Peters8485b562004-08-04 18:46:34 +00002005 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00002006 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00002007 if self.verbose:
2008 print "Running string", name
2009 (f,t) = self.testrunner.run(test)
2010 if self.verbose:
2011 print f, "of", t, "examples failed in string", name
2012 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002013
Tim Petersf3f57472004-08-08 06:11:48 +00002014 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00002015 f = t = 0
2016 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00002017 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00002018 for test in tests:
2019 (f2, t2) = self.testrunner.run(test)
2020 (f,t) = (f+f2, t+t2)
2021 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00002022
Tim Peters8485b562004-08-04 18:46:34 +00002023 def rundict(self, d, name, module=None):
2024 import new
2025 m = new.module(name)
2026 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00002027 if module is None:
2028 module = False
2029 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00002030
Tim Peters8485b562004-08-04 18:46:34 +00002031 def run__test__(self, d, name):
2032 import new
2033 m = new.module(name)
2034 m.__test__ = d
Tim Peters9661f9a2004-09-12 22:45:17 +00002035 return self.rundoc(m, name)
Tim Petersdb3756d2003-06-29 05:30:48 +00002036
Tim Peters8485b562004-08-04 18:46:34 +00002037 def summarize(self, verbose=None):
2038 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00002039
Tim Peters8485b562004-08-04 18:46:34 +00002040 def merge(self, other):
Tim Peters82076ef2004-09-13 00:52:51 +00002041 self.testrunner.merge(other.testrunner)
Tim Petersdb3756d2003-06-29 05:30:48 +00002042
Tim Peters8485b562004-08-04 18:46:34 +00002043######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002044## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002045######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002046
Jim Fultonf54bad42004-08-28 14:57:56 +00002047_unittest_reportflags = 0
Tim Peters38330fe2004-08-30 16:19:24 +00002048
Jim Fultonf54bad42004-08-28 14:57:56 +00002049def set_unittest_reportflags(flags):
Tim Peters38330fe2004-08-30 16:19:24 +00002050 """Sets the unittest option flags.
Jim Fultonf54bad42004-08-28 14:57:56 +00002051
2052 The old flag is returned so that a runner could restore the old
2053 value if it wished to:
2054
2055 >>> old = _unittest_reportflags
2056 >>> set_unittest_reportflags(REPORT_NDIFF |
2057 ... REPORT_ONLY_FIRST_FAILURE) == old
2058 True
2059
2060 >>> import doctest
2061 >>> doctest._unittest_reportflags == (REPORT_NDIFF |
2062 ... REPORT_ONLY_FIRST_FAILURE)
2063 True
Tim Petersdf7a2082004-08-29 00:38:17 +00002064
Jim Fultonf54bad42004-08-28 14:57:56 +00002065 Only reporting flags can be set:
2066
2067 >>> set_unittest_reportflags(ELLIPSIS)
2068 Traceback (most recent call last):
2069 ...
Tim Peters38330fe2004-08-30 16:19:24 +00002070 ValueError: ('Only reporting flags allowed', 8)
Jim Fultonf54bad42004-08-28 14:57:56 +00002071
2072 >>> set_unittest_reportflags(old) == (REPORT_NDIFF |
2073 ... REPORT_ONLY_FIRST_FAILURE)
2074 True
Jim Fultonf54bad42004-08-28 14:57:56 +00002075 """
Jim Fultonf54bad42004-08-28 14:57:56 +00002076 global _unittest_reportflags
Tim Peters38330fe2004-08-30 16:19:24 +00002077
2078 if (flags & REPORTING_FLAGS) != flags:
2079 raise ValueError("Only reporting flags allowed", flags)
Jim Fultonf54bad42004-08-28 14:57:56 +00002080 old = _unittest_reportflags
2081 _unittest_reportflags = flags
2082 return old
Tim Petersdf7a2082004-08-29 00:38:17 +00002083
Jim Fultonf54bad42004-08-28 14:57:56 +00002084
Tim Peters19397e52004-08-06 22:02:59 +00002085class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002086
Edward Loper34fcb142004-08-09 02:45:41 +00002087 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2088 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002089
Jim Fultona643b652004-07-14 19:06:50 +00002090 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002091 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002092 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002093 self._dt_test = test
2094 self._dt_setUp = setUp
2095 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002096
Jim Fultona643b652004-07-14 19:06:50 +00002097 def setUp(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002098 test = self._dt_test
Tim Petersdf7a2082004-08-29 00:38:17 +00002099
Tim Peters19397e52004-08-06 22:02:59 +00002100 if self._dt_setUp is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002101 self._dt_setUp(test)
Jim Fultona643b652004-07-14 19:06:50 +00002102
2103 def tearDown(self):
Jim Fultonf54bad42004-08-28 14:57:56 +00002104 test = self._dt_test
2105
Tim Peters19397e52004-08-06 22:02:59 +00002106 if self._dt_tearDown is not None:
Jim Fultonf54bad42004-08-28 14:57:56 +00002107 self._dt_tearDown(test)
2108
2109 test.globs.clear()
Jim Fultona643b652004-07-14 19:06:50 +00002110
2111 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002112 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002113 old = sys.stdout
2114 new = StringIO()
Jim Fultonf54bad42004-08-28 14:57:56 +00002115 optionflags = self._dt_optionflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002116
Tim Peters38330fe2004-08-30 16:19:24 +00002117 if not (optionflags & REPORTING_FLAGS):
Jim Fultonf54bad42004-08-28 14:57:56 +00002118 # The option flags don't include any reporting flags,
2119 # so add the default reporting flags
2120 optionflags |= _unittest_reportflags
Tim Petersdf7a2082004-08-29 00:38:17 +00002121
Jim Fultonf54bad42004-08-28 14:57:56 +00002122 runner = DocTestRunner(optionflags=optionflags,
Edward Loper34fcb142004-08-09 02:45:41 +00002123 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002124
Jim Fultona643b652004-07-14 19:06:50 +00002125 try:
Tim Peters19397e52004-08-06 22:02:59 +00002126 runner.DIVIDER = "-"*70
Jim Fultonf54bad42004-08-28 14:57:56 +00002127 failures, tries = runner.run(
2128 test, out=new.write, clear_globs=False)
Jim Fultona643b652004-07-14 19:06:50 +00002129 finally:
2130 sys.stdout = old
2131
2132 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002133 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002134
Tim Peters19397e52004-08-06 22:02:59 +00002135 def format_failure(self, err):
2136 test = self._dt_test
2137 if test.lineno is None:
2138 lineno = 'unknown line number'
2139 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002140 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002141 lname = '.'.join(test.name.split('.')[-1:])
2142 return ('Failed doctest test for %s\n'
2143 ' File "%s", line %s, in %s\n\n%s'
2144 % (test.name, test.filename, lineno, lname, err)
2145 )
2146
2147 def debug(self):
2148 r"""Run the test case without results and without catching exceptions
2149
2150 The unit test framework includes a debug method on test cases
2151 and test suites to support post-mortem debugging. The test code
2152 is run in such a way that errors are not caught. This way a
2153 caller can catch the errors and initiate post-mortem debugging.
2154
2155 The DocTestCase provides a debug method that raises
2156 UnexpectedException errors if there is an unexepcted
2157 exception:
2158
Edward Lopera1ef6112004-08-09 16:14:41 +00002159 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002160 ... {}, 'foo', 'foo.py', 0)
2161 >>> case = DocTestCase(test)
2162 >>> try:
2163 ... case.debug()
2164 ... except UnexpectedException, failure:
2165 ... pass
2166
2167 The UnexpectedException contains the test, the example, and
2168 the original exception:
2169
2170 >>> failure.test is test
2171 True
2172
2173 >>> failure.example.want
2174 '42\n'
2175
2176 >>> exc_info = failure.exc_info
2177 >>> raise exc_info[0], exc_info[1], exc_info[2]
2178 Traceback (most recent call last):
2179 ...
2180 KeyError
2181
2182 If the output doesn't match, then a DocTestFailure is raised:
2183
Edward Lopera1ef6112004-08-09 16:14:41 +00002184 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002185 ... >>> x = 1
2186 ... >>> x
2187 ... 2
2188 ... ''', {}, 'foo', 'foo.py', 0)
2189 >>> case = DocTestCase(test)
2190
2191 >>> try:
2192 ... case.debug()
2193 ... except DocTestFailure, failure:
2194 ... pass
2195
2196 DocTestFailure objects provide access to the test:
2197
2198 >>> failure.test is test
2199 True
2200
2201 As well as to the example:
2202
2203 >>> failure.example.want
2204 '2\n'
2205
2206 and the actual output:
2207
2208 >>> failure.got
2209 '1\n'
2210
2211 """
2212
Jim Fultonf54bad42004-08-28 14:57:56 +00002213 self.setUp()
Edward Loper34fcb142004-08-09 02:45:41 +00002214 runner = DebugRunner(optionflags=self._dt_optionflags,
2215 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002216 runner.run(self._dt_test)
Jim Fultonf54bad42004-08-28 14:57:56 +00002217 self.tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002218
2219 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002220 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002221
2222 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002223 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002224 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2225
2226 __str__ = __repr__
2227
2228 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002229 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002230
Jim Fultonf54bad42004-08-28 14:57:56 +00002231def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
2232 **options):
Tim Peters8485b562004-08-04 18:46:34 +00002233 """
Tim Peters75dc5e12004-08-22 17:50:45 +00002234 Convert doctest tests for a module to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002235
Tim Peters19397e52004-08-06 22:02:59 +00002236 This converts each documentation string in a module that
2237 contains doctest tests to a unittest test case. If any of the
2238 tests in a doc string fail, then the test case fails. An exception
2239 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002240 (sometimes approximate) line number.
2241
Tim Peters19397e52004-08-06 22:02:59 +00002242 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002243 can be either a module or a module name.
2244
2245 If no argument is given, the calling module is used.
Jim Fultonf54bad42004-08-28 14:57:56 +00002246
2247 A number of options may be provided as keyword arguments:
2248
2249 package
2250 The name of a Python package. Text-file paths will be
2251 interpreted relative to the directory containing this package.
2252 The package may be supplied as a package object or as a dotted
2253 package name.
2254
2255 setUp
2256 The name of a set-up function. This is called before running the
2257 tests in each file. The setUp function will be passed a DocTest
2258 object. The setUp function can access the test globals as the
2259 globs attribute of the test passed.
2260
2261 tearDown
2262 The name of a tear-down function. This is called after running the
2263 tests in each file. The tearDown function will be passed a DocTest
2264 object. The tearDown function can access the test globals as the
2265 globs attribute of the test passed.
2266
2267 globs
2268 A dictionary containing initial global variables for the tests.
2269
2270 optionflags
2271 A set of doctest option flags expressed as an integer.
Jim Fultona643b652004-07-14 19:06:50 +00002272 """
Jim Fultona643b652004-07-14 19:06:50 +00002273
Tim Peters8485b562004-08-04 18:46:34 +00002274 if test_finder is None:
2275 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002276
Tim Peters19397e52004-08-06 22:02:59 +00002277 module = _normalize_module(module)
2278 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2279 if globs is None:
2280 globs = module.__dict__
Jim Fultonf54bad42004-08-28 14:57:56 +00002281 if not tests:
2282 # Why do we want to do this? Because it reveals a bug that might
2283 # otherwise be hidden.
Tim Peters19397e52004-08-06 22:02:59 +00002284 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002285
2286 tests.sort()
2287 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002288 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002289 if len(test.examples) == 0:
2290 continue
Tim Peters8485b562004-08-04 18:46:34 +00002291 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002292 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002293 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002294 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002295 test.filename = filename
Jim Fultonf54bad42004-08-28 14:57:56 +00002296 suite.addTest(DocTestCase(test, **options))
Tim Peters19397e52004-08-06 22:02:59 +00002297
2298 return suite
2299
2300class DocFileCase(DocTestCase):
2301
2302 def id(self):
2303 return '_'.join(self._dt_test.name.split('.'))
2304
2305 def __repr__(self):
2306 return self._dt_test.filename
2307 __str__ = __repr__
2308
2309 def format_failure(self, err):
2310 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2311 % (self._dt_test.name, self._dt_test.filename, err)
2312 )
2313
Jim Fultonf54bad42004-08-28 14:57:56 +00002314def DocFileTest(path, package=None, globs=None, **options):
Tim Peters19397e52004-08-06 22:02:59 +00002315 package = _normalize_module(package)
2316 name = path.split('/')[-1]
2317 dir = os.path.split(package.__file__)[0]
2318 path = os.path.join(dir, *(path.split('/')))
2319 doc = open(path).read()
2320
2321 if globs is None:
2322 globs = {}
2323
Edward Lopera1ef6112004-08-09 16:14:41 +00002324 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002325
Jim Fultonf54bad42004-08-28 14:57:56 +00002326 return DocFileCase(test, **options)
Tim Peters19397e52004-08-06 22:02:59 +00002327
2328def DocFileSuite(*paths, **kw):
2329 """Creates a suite of doctest files.
2330
2331 One or more text file paths are given as strings. These should
2332 use "/" characters to separate path segments. Paths are relative
2333 to the directory of the calling module, or relative to the package
2334 passed as a keyword argument.
2335
2336 A number of options may be provided as keyword arguments:
2337
2338 package
2339 The name of a Python package. Text-file paths will be
2340 interpreted relative to the directory containing this package.
2341 The package may be supplied as a package object or as a dotted
2342 package name.
2343
2344 setUp
2345 The name of a set-up function. This is called before running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002346 tests in each file. The setUp function will be passed a DocTest
2347 object. The setUp function can access the test globals as the
2348 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002349
2350 tearDown
2351 The name of a tear-down function. This is called after running the
Jim Fultonf54bad42004-08-28 14:57:56 +00002352 tests in each file. The tearDown function will be passed a DocTest
2353 object. The tearDown function can access the test globals as the
2354 globs attribute of the test passed.
Tim Peters19397e52004-08-06 22:02:59 +00002355
2356 globs
2357 A dictionary containing initial global variables for the tests.
Jim Fultonf54bad42004-08-28 14:57:56 +00002358
2359 optionflags
2360 A set of doctest option flags expressed as an integer.
Tim Petersdf7a2082004-08-29 00:38:17 +00002361
Tim Peters19397e52004-08-06 22:02:59 +00002362 """
2363 suite = unittest.TestSuite()
2364
2365 # We do this here so that _normalize_module is called at the right
2366 # level. If it were called in DocFileTest, then this function
2367 # would be the caller and we might guess the package incorrectly.
2368 kw['package'] = _normalize_module(kw.get('package'))
2369
2370 for path in paths:
2371 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002372
Tim Petersdb3756d2003-06-29 05:30:48 +00002373 return suite
2374
Tim Peters8485b562004-08-04 18:46:34 +00002375######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002376## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002377######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002378
Tim Peters19397e52004-08-06 22:02:59 +00002379def script_from_examples(s):
2380 r"""Extract script from text with examples.
2381
2382 Converts text with examples to a Python script. Example input is
2383 converted to regular code. Example output and all other words
2384 are converted to comments:
2385
2386 >>> text = '''
2387 ... Here are examples of simple math.
2388 ...
2389 ... Python has super accurate integer addition
2390 ...
2391 ... >>> 2 + 2
2392 ... 5
2393 ...
2394 ... And very friendly error messages:
2395 ...
2396 ... >>> 1/0
2397 ... To Infinity
2398 ... And
2399 ... Beyond
2400 ...
2401 ... You can use logic if you want:
2402 ...
2403 ... >>> if 0:
2404 ... ... blah
2405 ... ... blah
2406 ... ...
2407 ...
2408 ... Ho hum
2409 ... '''
2410
2411 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002412 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002413 #
Edward Lopera5db6002004-08-12 02:41:30 +00002414 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002415 #
2416 2 + 2
2417 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002418 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002419 #
Edward Lopera5db6002004-08-12 02:41:30 +00002420 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002421 #
2422 1/0
2423 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002424 ## To Infinity
2425 ## And
2426 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002427 #
Edward Lopera5db6002004-08-12 02:41:30 +00002428 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002429 #
2430 if 0:
2431 blah
2432 blah
Tim Peters19397e52004-08-06 22:02:59 +00002433 #
Edward Lopera5db6002004-08-12 02:41:30 +00002434 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002435 """
Edward Loper00f8da72004-08-26 18:05:07 +00002436 output = []
2437 for piece in DocTestParser().parse(s):
2438 if isinstance(piece, Example):
2439 # Add the example's source code (strip trailing NL)
2440 output.append(piece.source[:-1])
2441 # Add the expected output:
2442 want = piece.want
2443 if want:
2444 output.append('# Expected:')
2445 output += ['## '+l for l in want.split('\n')[:-1]]
2446 else:
2447 # Add non-example text.
2448 output += [_comment_line(l)
2449 for l in piece.split('\n')[:-1]]
Tim Peters19397e52004-08-06 22:02:59 +00002450
Edward Loper00f8da72004-08-26 18:05:07 +00002451 # Trim junk on both ends.
2452 while output and output[-1] == '#':
2453 output.pop()
2454 while output and output[0] == '#':
2455 output.pop(0)
2456 # Combine the output, and return it.
2457 return '\n'.join(output)
Tim Petersdb3756d2003-06-29 05:30:48 +00002458
2459def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002460 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002461
2462 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002463 test to be debugged and the name (within the module) of the object
2464 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002465 """
Tim Peters8485b562004-08-04 18:46:34 +00002466 module = _normalize_module(module)
2467 tests = DocTestFinder().find(module)
2468 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002469 if not test:
2470 raise ValueError(name, "not found in tests")
2471 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002472 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002473 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002474
Jim Fultona643b652004-07-14 19:06:50 +00002475def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002476 """Debug a single doctest docstring, in argument `src`'"""
2477 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002478 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002479
Jim Fultona643b652004-07-14 19:06:50 +00002480def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002481 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002482 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002483
Tim Petersb6a04d62004-08-23 21:37:56 +00002484 # Note that tempfile.NameTemporaryFile() cannot be used. As the
2485 # docs say, a file so created cannot be opened by name a second time
2486 # on modern Windows boxes, and execfile() needs to open it.
2487 srcfilename = tempfile.mktemp(".py", "doctestdebug")
Tim Peters8485b562004-08-04 18:46:34 +00002488 f = open(srcfilename, 'w')
2489 f.write(src)
2490 f.close()
2491
Tim Petersb6a04d62004-08-23 21:37:56 +00002492 try:
2493 if globs:
2494 globs = globs.copy()
2495 else:
2496 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002497
Tim Petersb6a04d62004-08-23 21:37:56 +00002498 if pm:
2499 try:
2500 execfile(srcfilename, globs, globs)
2501 except:
2502 print sys.exc_info()[1]
2503 pdb.post_mortem(sys.exc_info()[2])
2504 else:
2505 # Note that %r is vital here. '%s' instead can, e.g., cause
2506 # backslashes to get treated as metacharacters on Windows.
2507 pdb.run("execfile(%r)" % srcfilename, globs, globs)
2508
2509 finally:
2510 os.remove(srcfilename)
Tim Petersdb3756d2003-06-29 05:30:48 +00002511
Jim Fultona643b652004-07-14 19:06:50 +00002512def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002513 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002514
2515 Provide the module (or dotted name of the module) containing the
2516 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002517 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002518 """
Tim Peters8485b562004-08-04 18:46:34 +00002519 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002520 testsrc = testsource(module, name)
2521 debug_script(testsrc, pm, module.__dict__)
2522
Tim Peters8485b562004-08-04 18:46:34 +00002523######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002524## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002525######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002526class _TestClass:
2527 """
2528 A pointless class, for sanity-checking of docstring testing.
2529
2530 Methods:
2531 square()
2532 get()
2533
2534 >>> _TestClass(13).get() + _TestClass(-12).get()
2535 1
2536 >>> hex(_TestClass(13).square().get())
2537 '0xa9'
2538 """
2539
2540 def __init__(self, val):
2541 """val -> _TestClass object with associated value val.
2542
2543 >>> t = _TestClass(123)
2544 >>> print t.get()
2545 123
2546 """
2547
2548 self.val = val
2549
2550 def square(self):
2551 """square() -> square TestClass's associated value
2552
2553 >>> _TestClass(13).square().get()
2554 169
2555 """
2556
2557 self.val = self.val ** 2
2558 return self
2559
2560 def get(self):
2561 """get() -> return TestClass's associated value.
2562
2563 >>> x = _TestClass(-42)
2564 >>> print x.get()
2565 -42
2566 """
2567
2568 return self.val
2569
2570__test__ = {"_TestClass": _TestClass,
2571 "string": r"""
2572 Example of a string object, searched as-is.
2573 >>> x = 1; y = 2
2574 >>> x + y, x * y
2575 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002576 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002577
Tim Peters6ebe61f2003-06-27 20:48:05 +00002578 "bool-int equivalence": r"""
2579 In 2.2, boolean expressions displayed
2580 0 or 1. By default, we still accept
2581 them. This can be disabled by passing
2582 DONT_ACCEPT_TRUE_FOR_1 to the new
2583 optionflags argument.
2584 >>> 4 == 4
2585 1
2586 >>> 4 == 4
2587 True
2588 >>> 4 > 4
2589 0
2590 >>> 4 > 4
2591 False
2592 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002593
Tim Peters8485b562004-08-04 18:46:34 +00002594 "blank lines": r"""
Tim Peters3fa8c202004-08-23 21:43:39 +00002595 Blank lines can be marked with <BLANKLINE>:
2596 >>> print 'foo\n\nbar\n'
2597 foo
2598 <BLANKLINE>
2599 bar
2600 <BLANKLINE>
Tim Peters8485b562004-08-04 18:46:34 +00002601 """,
Tim Peters3fa8c202004-08-23 21:43:39 +00002602
2603 "ellipsis": r"""
2604 If the ellipsis flag is used, then '...' can be used to
2605 elide substrings in the desired output:
2606 >>> print range(1000) #doctest: +ELLIPSIS
2607 [0, 1, 2, ..., 999]
2608 """,
2609
2610 "whitespace normalization": r"""
2611 If the whitespace normalization flag is used, then
2612 differences in whitespace are ignored.
2613 >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
2614 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2615 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2616 27, 28, 29]
2617 """,
2618 }
Tim Peters8485b562004-08-04 18:46:34 +00002619
Tim Peters8a7d2d52001-01-16 07:10:57 +00002620def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002621 r = unittest.TextTestRunner()
2622 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002623
2624if __name__ == "__main__":
2625 _test()