blob: ccf976cb1ec593a1aabe3807150679018d6b0c3f [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',
179 'UNIFIED_DIFF',
180 'CONTEXT_DIFF',
181 # 1. Utility Functions
Tim Peters8485b562004-08-04 18:46:34 +0000182 'is_private',
Edward Loperb7503ff2004-08-19 19:19:03 +0000183 # 2. Example & DocTest
Tim Peters8485b562004-08-04 18:46:34 +0000184 'Example',
185 'DocTest',
Edward Loperb7503ff2004-08-19 19:19:03 +0000186 # 3. Doctest Parser
187 'DocTestParser',
188 # 4. Doctest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000189 'DocTestFinder',
Edward Loperb7503ff2004-08-19 19:19:03 +0000190 # 5. Doctest Runner
Tim Peters8485b562004-08-04 18:46:34 +0000191 'DocTestRunner',
Edward Loperb7503ff2004-08-19 19:19:03 +0000192 'OutputChecker',
193 'DocTestFailure',
194 'UnexpectedException',
195 'DebugRunner',
196 # 6. Test Functions
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000197 'testmod',
198 'run_docstring_examples',
Edward Loperb7503ff2004-08-19 19:19:03 +0000199 # 7. Tester
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000200 'Tester',
Edward Loperb7503ff2004-08-19 19:19:03 +0000201 # 8. Unittest Support
Tim Peters19397e52004-08-06 22:02:59 +0000202 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000203 'DocTestSuite',
Edward Loperb7503ff2004-08-19 19:19:03 +0000204 'DocFileCase',
205 'DocFileTest',
206 'DocFileSuite',
207 # 9. Debugging Support
208 'script_from_examples',
Tim Petersdb3756d2003-06-29 05:30:48 +0000209 'testsource',
Edward Loperb7503ff2004-08-19 19:19:03 +0000210 'debug_src',
211 'debug_script',
Tim Petersdb3756d2003-06-29 05:30:48 +0000212 'debug',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000213]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000214
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000215import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000216
Tim Peters19397e52004-08-06 22:02:59 +0000217import sys, traceback, inspect, linecache, os, re, types
Jim Fulton356fd192004-08-09 11:34:47 +0000218import unittest, difflib, pdb, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000219import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000220from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000221
Jim Fulton356fd192004-08-09 11:34:47 +0000222real_pdb_set_trace = pdb.set_trace
223
Tim Peters19397e52004-08-06 22:02:59 +0000224# There are 4 basic classes:
225# - Example: a <source, want> pair, plus an intra-docstring line number.
226# - DocTest: a collection of examples, parsed from a docstring, plus
227# info about where the docstring came from (name, filename, lineno).
228# - DocTestFinder: extracts DocTests from a given object's docstring and
229# its contained objects' docstrings.
230# - DocTestRunner: runs DocTest cases, and accumulates statistics.
231#
232# So the basic picture is:
233#
234# list of:
235# +------+ +---------+ +-------+
236# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
237# +------+ +---------+ +-------+
238# | Example |
239# | ... |
240# | Example |
241# +---------+
242
Edward Loperac20f572004-08-12 02:02:24 +0000243# Option constants.
244OPTIONFLAGS_BY_NAME = {}
245def register_optionflag(name):
246 flag = 1 << len(OPTIONFLAGS_BY_NAME)
247 OPTIONFLAGS_BY_NAME[name] = flag
248 return flag
249
250DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
251DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
252NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
253ELLIPSIS = register_optionflag('ELLIPSIS')
254UNIFIED_DIFF = register_optionflag('UNIFIED_DIFF')
255CONTEXT_DIFF = register_optionflag('CONTEXT_DIFF')
256
257# Special string markers for use in `want` strings:
258BLANKLINE_MARKER = '<BLANKLINE>'
259ELLIPSIS_MARKER = '...'
260
Tim Peters8485b562004-08-04 18:46:34 +0000261######################################################################
262## Table of Contents
263######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000264# 1. Utility Functions
265# 2. Example & DocTest -- store test cases
266# 3. DocTest Parser -- extracts examples from strings
267# 4. DocTest Finder -- extracts test cases from objects
268# 5. DocTest Runner -- runs test cases
269# 6. Test Functions -- convenient wrappers for testing
270# 7. Tester Class -- for backwards compatibility
271# 8. Unittest Support
272# 9. Debugging Support
273# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000274
Tim Peters8485b562004-08-04 18:46:34 +0000275######################################################################
276## 1. Utility Functions
277######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000278
279def is_private(prefix, base):
280 """prefix, base -> true iff name prefix + "." + base is "private".
281
282 Prefix may be an empty string, and base does not contain a period.
283 Prefix is ignored (although functions you write conforming to this
284 protocol may make use of it).
285 Return true iff base begins with an (at least one) underscore, but
286 does not both begin and end with (at least) two underscores.
287
Tim Petersbafb1fe2004-08-08 01:52:57 +0000288 >>> warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
289 ... "doctest", 0)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000290 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000291 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000292 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000293 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000294 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000295 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000296 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000297 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000298 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000299 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000300 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000301 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000302 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000303 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000304 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000305 warnings.warn("is_private is deprecated; it wasn't useful; "
306 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000307 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000308 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
309
Tim Peters8485b562004-08-04 18:46:34 +0000310def _extract_future_flags(globs):
311 """
312 Return the compiler-flags associated with the future features that
313 have been imported into the given namespace (globs).
314 """
315 flags = 0
316 for fname in __future__.all_feature_names:
317 feature = globs.get(fname, None)
318 if feature is getattr(__future__, fname):
319 flags |= feature.compiler_flag
320 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000321
Tim Peters8485b562004-08-04 18:46:34 +0000322def _normalize_module(module, depth=2):
323 """
324 Return the module specified by `module`. In particular:
325 - If `module` is a module, then return module.
326 - If `module` is a string, then import and return the
327 module with that name.
328 - If `module` is None, then return the calling module.
329 The calling module is assumed to be the module of
330 the stack frame at the given depth in the call stack.
331 """
332 if inspect.ismodule(module):
333 return module
334 elif isinstance(module, (str, unicode)):
335 return __import__(module, globals(), locals(), ["*"])
336 elif module is None:
337 return sys.modules[sys._getframe(depth).f_globals['__name__']]
338 else:
339 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000340
Edward Lopera1ef6112004-08-09 16:14:41 +0000341def _tag_msg(tag, msg, indent=' '):
Tim Peters8485b562004-08-04 18:46:34 +0000342 """
343 Return a string that displays a tag-and-message pair nicely,
344 keeping the tag and its message on the same line when that
Edward Lopera1ef6112004-08-09 16:14:41 +0000345 makes sense. If the message is displayed on separate lines,
346 then `indent` is added to the beginning of each line.
Tim Peters8485b562004-08-04 18:46:34 +0000347 """
Tim Peters8485b562004-08-04 18:46:34 +0000348 # If the message doesn't end in a newline, then add one.
349 if msg[-1:] != '\n':
350 msg += '\n'
351 # If the message is short enough, and contains no internal
352 # newlines, then display it on the same line as the tag.
353 # Otherwise, display the tag on its own line.
354 if (len(tag) + len(msg) < 75 and
355 msg.find('\n', 0, len(msg)-1) == -1):
356 return '%s: %s' % (tag, msg)
357 else:
Edward Lopera1ef6112004-08-09 16:14:41 +0000358 msg = '\n'.join([indent+l for l in msg[:-1].split('\n')])
359 return '%s:\n%s\n' % (tag, msg)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000360
Edward Loper8e4a34b2004-08-12 02:34:27 +0000361def _exception_traceback(exc_info):
362 """
363 Return a string containing a traceback message for the given
364 exc_info tuple (as returned by sys.exc_info()).
365 """
366 # Get a traceback message.
367 excout = StringIO()
368 exc_type, exc_val, exc_tb = exc_info
369 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
370 return excout.getvalue()
371
Tim Peters8485b562004-08-04 18:46:34 +0000372# Override some StringIO methods.
373class _SpoofOut(StringIO):
374 def getvalue(self):
375 result = StringIO.getvalue(self)
376 # If anything at all was written, make sure there's a trailing
377 # newline. There's no way for the expected output to indicate
378 # that a trailing newline is missing.
379 if result and not result.endswith("\n"):
380 result += "\n"
381 # Prevent softspace from screwing up the next test case, in
382 # case they used print with a trailing comma in an example.
383 if hasattr(self, "softspace"):
384 del self.softspace
385 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000386
Tim Peters8485b562004-08-04 18:46:34 +0000387 def truncate(self, size=None):
388 StringIO.truncate(self, size)
389 if hasattr(self, "softspace"):
390 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000391
Tim Peters26b3ebb2004-08-19 08:10:08 +0000392# Worst-case linear-time ellipsis matching.
Tim Petersb0a04e12004-08-20 02:08:04 +0000393def _ellipsis_match(want, got):
Tim Petersdc5de3b2004-08-19 14:06:20 +0000394 """
395 Essentially the only subtle case:
Tim Petersb0a04e12004-08-20 02:08:04 +0000396 >>> _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000397 False
398 """
Tim Peters26b3ebb2004-08-19 08:10:08 +0000399 if ELLIPSIS_MARKER not in want:
400 return want == got
Tim Petersdc5de3b2004-08-19 14:06:20 +0000401
Tim Peters26b3ebb2004-08-19 08:10:08 +0000402 # Find "the real" strings.
403 ws = want.split(ELLIPSIS_MARKER)
404 assert len(ws) >= 2
Tim Peters26b3ebb2004-08-19 08:10:08 +0000405
Tim Petersdc5de3b2004-08-19 14:06:20 +0000406 # Deal with exact matches possibly needed at one or both ends.
407 startpos, endpos = 0, len(got)
408 w = ws[0]
409 if w: # starts with exact match
410 if got.startswith(w):
411 startpos = len(w)
412 del ws[0]
413 else:
414 return False
415 w = ws[-1]
416 if w: # ends with exact match
417 if got.endswith(w):
418 endpos -= len(w)
419 del ws[-1]
420 else:
421 return False
422
423 if startpos > endpos:
424 # Exact end matches required more characters than we have, as in
Tim Petersb0a04e12004-08-20 02:08:04 +0000425 # _ellipsis_match('aa...aa', 'aaa')
Tim Petersdc5de3b2004-08-19 14:06:20 +0000426 return False
427
428 # For the rest, we only need to find the leftmost non-overlapping
429 # match for each piece. If there's no overall match that way alone,
430 # there's no overall match period.
Tim Peters26b3ebb2004-08-19 08:10:08 +0000431 for w in ws:
432 # w may be '' at times, if there are consecutive ellipses, or
433 # due to an ellipsis at the start or end of `want`. That's OK.
Tim Petersdc5de3b2004-08-19 14:06:20 +0000434 # Search for an empty string succeeds, and doesn't change startpos.
435 startpos = got.find(w, startpos, endpos)
436 if startpos < 0:
Tim Peters26b3ebb2004-08-19 08:10:08 +0000437 return False
Tim Petersdc5de3b2004-08-19 14:06:20 +0000438 startpos += len(w)
Tim Peters26b3ebb2004-08-19 08:10:08 +0000439
Tim Petersdc5de3b2004-08-19 14:06:20 +0000440 return True
Tim Peters26b3ebb2004-08-19 08:10:08 +0000441
Tim Peters8485b562004-08-04 18:46:34 +0000442######################################################################
443## 2. Example & DocTest
444######################################################################
445## - An "example" is a <source, want> pair, where "source" is a
446## fragment of source code, and "want" is the expected output for
447## "source." The Example class also includes information about
448## where the example was extracted from.
449##
Edward Lopera1ef6112004-08-09 16:14:41 +0000450## - A "doctest" is a collection of examples, typically extracted from
451## a string (such as an object's docstring). The DocTest class also
452## includes information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000453
Tim Peters8485b562004-08-04 18:46:34 +0000454class Example:
455 """
456 A single doctest example, consisting of source code and expected
Edward Lopera1ef6112004-08-09 16:14:41 +0000457 output. `Example` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000458
Edward Loper74bca7a2004-08-12 02:27:44 +0000459 - source: A single Python statement, always ending with a newline.
Tim Petersbb431472004-08-09 03:51:46 +0000460 The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000461
Edward Loper74bca7a2004-08-12 02:27:44 +0000462 - want: The expected output from running the source code (either
Tim Petersbb431472004-08-09 03:51:46 +0000463 from stdout, or a traceback in case of exception). `want` ends
464 with a newline unless it's empty, in which case it's an empty
465 string. The constructor adds a newline if needed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000466
Edward Loper74bca7a2004-08-12 02:27:44 +0000467 - lineno: The line number within the DocTest string containing
Tim Peters8485b562004-08-04 18:46:34 +0000468 this Example where the Example begins. This line number is
469 zero-based, with respect to the beginning of the DocTest.
Edward Loper74bca7a2004-08-12 02:27:44 +0000470
471 - indent: The example's indentation in the DocTest string.
472 I.e., the number of space characters that preceed the
473 example's first prompt.
474
475 - options: A dictionary mapping from option flags to True or
476 False, which is used to override default options for this
477 example. Any option flags not contained in this dictionary
478 are left at their default value (as specified by the
479 DocTestRunner's optionflags). By default, no options are set.
Tim Peters8485b562004-08-04 18:46:34 +0000480 """
Edward Loper74bca7a2004-08-12 02:27:44 +0000481 def __init__(self, source, want, lineno, indent=0, options=None):
Tim Petersbb431472004-08-09 03:51:46 +0000482 # Normalize inputs.
483 if not source.endswith('\n'):
484 source += '\n'
485 if want and not want.endswith('\n'):
486 want += '\n'
Tim Peters8485b562004-08-04 18:46:34 +0000487 # Store properties.
488 self.source = source
489 self.want = want
490 self.lineno = lineno
Edward Loper74bca7a2004-08-12 02:27:44 +0000491 self.indent = indent
492 if options is None: options = {}
493 self.options = options
Tim Peters8a7d2d52001-01-16 07:10:57 +0000494
Tim Peters8485b562004-08-04 18:46:34 +0000495class DocTest:
496 """
497 A collection of doctest examples that should be run in a single
Edward Lopera1ef6112004-08-09 16:14:41 +0000498 namespace. Each `DocTest` defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000499
Tim Peters8485b562004-08-04 18:46:34 +0000500 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000501
Tim Peters8485b562004-08-04 18:46:34 +0000502 - globs: The namespace (aka globals) that the examples should
503 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000504
Tim Peters8485b562004-08-04 18:46:34 +0000505 - name: A name identifying the DocTest (typically, the name of
506 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000507
Tim Peters8485b562004-08-04 18:46:34 +0000508 - filename: The name of the file that this DocTest was extracted
Edward Lopera1ef6112004-08-09 16:14:41 +0000509 from, or `None` if the filename is unknown.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000510
Tim Peters8485b562004-08-04 18:46:34 +0000511 - lineno: The line number within filename where this DocTest
Edward Lopera1ef6112004-08-09 16:14:41 +0000512 begins, or `None` if the line number is unavailable. This
513 line number is zero-based, with respect to the beginning of
514 the file.
515
516 - docstring: The string that the examples were extracted from,
517 or `None` if the string is unavailable.
Tim Peters8485b562004-08-04 18:46:34 +0000518 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000519 def __init__(self, examples, globs, name, filename, lineno, docstring):
Tim Peters8485b562004-08-04 18:46:34 +0000520 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000521 Create a new DocTest containing the given examples. The
522 DocTest's globals are initialized with a copy of `globs`.
Tim Peters8485b562004-08-04 18:46:34 +0000523 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000524 assert not isinstance(examples, basestring), \
525 "DocTest no longer accepts str; use DocTestParser instead"
526 self.examples = examples
527 self.docstring = docstring
Tim Peters8485b562004-08-04 18:46:34 +0000528 self.globs = globs.copy()
Tim Peters8485b562004-08-04 18:46:34 +0000529 self.name = name
530 self.filename = filename
531 self.lineno = lineno
Tim Peters8485b562004-08-04 18:46:34 +0000532
533 def __repr__(self):
534 if len(self.examples) == 0:
535 examples = 'no examples'
536 elif len(self.examples) == 1:
537 examples = '1 example'
538 else:
539 examples = '%d examples' % len(self.examples)
540 return ('<DocTest %s from %s:%s (%s)>' %
541 (self.name, self.filename, self.lineno, examples))
542
543
544 # This lets us sort tests by name:
545 def __cmp__(self, other):
546 if not isinstance(other, DocTest):
547 return -1
548 return cmp((self.name, self.filename, self.lineno, id(self)),
549 (other.name, other.filename, other.lineno, id(other)))
550
551######################################################################
Edward Loperb7503ff2004-08-19 19:19:03 +0000552## 3. DocTestParser
Edward Loper7c748462004-08-09 02:06:06 +0000553######################################################################
554
Edward Lopera1ef6112004-08-09 16:14:41 +0000555class DocTestParser:
Edward Loper7c748462004-08-09 02:06:06 +0000556 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000557 A class used to parse strings containing doctest examples.
Edward Loper7c748462004-08-09 02:06:06 +0000558 """
Edward Loper8e4a34b2004-08-12 02:34:27 +0000559 # This regular expression is used to find doctest examples in a
560 # string. It defines three groups: `source` is the source code
561 # (including leading indentation and prompts); `indent` is the
562 # indentation of the first (PS1) line of the source code; and
563 # `want` is the expected output (including leading indentation).
Edward Loper7c748462004-08-09 02:06:06 +0000564 _EXAMPLE_RE = re.compile(r'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000565 # Source consists of a PS1 line followed by zero or more PS2 lines.
566 (?P<source>
567 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
568 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
569 \n?
570 # Want consists of any non-blank lines that do not start with PS1.
571 (?P<want> (?:(?![ ]*$) # Not a blank line
572 (?![ ]*>>>) # Not a line starting with PS1
573 .*$\n? # But any other line
574 )*)
575 ''', re.MULTILINE | re.VERBOSE)
Edward Loper8e4a34b2004-08-12 02:34:27 +0000576
Tim Peters7ea48dd2004-08-13 01:52:59 +0000577 # A callable returning a true value iff its argument is a blank line
578 # or contains a single comment.
Edward Loper8e4a34b2004-08-12 02:34:27 +0000579 _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000580
Edward Lopera1ef6112004-08-09 16:14:41 +0000581 def get_doctest(self, string, globs, name, filename, lineno):
Edward Loper7c748462004-08-09 02:06:06 +0000582 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000583 Extract all doctest examples from the given string, and
584 collect them into a `DocTest` object.
585
586 `globs`, `name`, `filename`, and `lineno` are attributes for
587 the new `DocTest` object. See the documentation for `DocTest`
588 for more information.
589 """
590 return DocTest(self.get_examples(string, name), globs,
591 name, filename, lineno, string)
592
593 def get_examples(self, string, name='<string>'):
594 """
595 Extract all doctest examples from the given string, and return
596 them as a list of `Example` objects. Line numbers are
597 0-based, because it's most common in doctests that nothing
598 interesting appears on the same line as opening triple-quote,
599 and so the first interesting line is called \"line 1\" then.
600
601 The optional argument `name` is a name identifying this
602 string, and is only used for error messages.
Edward Loper7c748462004-08-09 02:06:06 +0000603
604 >>> text = '''
605 ... >>> x, y = 2, 3 # no output expected
606 ... >>> if 1:
607 ... ... print x
608 ... ... print y
609 ... 2
610 ... 3
611 ...
612 ... Some text.
613 ... >>> x+y
614 ... 5
615 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000616 >>> for x in DocTestParser().get_examples(text):
Edward Loper78b58f32004-08-09 02:56:02 +0000617 ... print (x.source, x.want, x.lineno)
Tim Petersbb431472004-08-09 03:51:46 +0000618 ('x, y = 2, 3 # no output expected\\n', '', 1)
Edward Loper7c748462004-08-09 02:06:06 +0000619 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
Tim Petersbb431472004-08-09 03:51:46 +0000620 ('x+y\\n', '5\\n', 9)
Edward Loper7c748462004-08-09 02:06:06 +0000621 """
622 examples = []
623 charno, lineno = 0, 0
624 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000625 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000626 # Update lineno (lines before this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000627 lineno += string.count('\n', charno, m.start())
Edward Loper7c748462004-08-09 02:06:06 +0000628 # Extract source/want from the regexp match.
Edward Lopera1ef6112004-08-09 16:14:41 +0000629 (source, want) = self._parse_example(m, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000630 # Extract extra options from the source.
631 options = self._find_options(source, name, lineno)
Edward Loper74bca7a2004-08-12 02:27:44 +0000632 # Create an Example, and add it to the list.
Edward Loperb51b2342004-08-17 16:37:12 +0000633 if not self._IS_BLANK_OR_COMMENT(source):
634 examples.append( Example(source, want, lineno,
635 len(m.group('indent')), options) )
Edward Loper7c748462004-08-09 02:06:06 +0000636 # Update lineno (lines inside this example)
Edward Lopera1ef6112004-08-09 16:14:41 +0000637 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000638 # Update charno.
639 charno = m.end()
640 return examples
641
Edward Lopera1ef6112004-08-09 16:14:41 +0000642 def get_program(self, string, name="<string>"):
Edward Loper7c748462004-08-09 02:06:06 +0000643 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000644 Return an executable program from the given string, as a string.
Edward Loper7c748462004-08-09 02:06:06 +0000645
646 The format of this isn't rigidly defined. In general, doctest
647 examples become the executable statements in the result, and
648 their expected outputs become comments, preceded by an \"#Expected:\"
649 comment. Everything else (text, comments, everything not part of
650 a doctest test) is also placed in comments.
651
Edward Lopera1ef6112004-08-09 16:14:41 +0000652 The optional argument `name` is a name identifying this
653 string, and is only used for error messages.
654
Edward Loper7c748462004-08-09 02:06:06 +0000655 >>> text = '''
656 ... >>> x, y = 2, 3 # no output expected
657 ... >>> if 1:
658 ... ... print x
659 ... ... print y
660 ... 2
661 ... 3
662 ...
663 ... Some text.
664 ... >>> x+y
665 ... 5
666 ... '''
Edward Lopera1ef6112004-08-09 16:14:41 +0000667 >>> print DocTestParser().get_program(text)
Edward Loper7c748462004-08-09 02:06:06 +0000668 x, y = 2, 3 # no output expected
669 if 1:
670 print x
671 print y
672 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000673 ## 2
674 ## 3
Edward Loper7c748462004-08-09 02:06:06 +0000675 #
Edward Lopera5db6002004-08-12 02:41:30 +0000676 # Some text.
Edward Loper7c748462004-08-09 02:06:06 +0000677 x+y
678 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +0000679 ## 5
Edward Loper7c748462004-08-09 02:06:06 +0000680 """
Edward Lopera5db6002004-08-12 02:41:30 +0000681 string = string.expandtabs()
682 # If all lines begin with the same indentation, then strip it.
683 min_indent = self._min_indent(string)
684 if min_indent > 0:
685 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
686
Edward Loper7c748462004-08-09 02:06:06 +0000687 output = []
688 charnum, lineno = 0, 0
689 # Find all doctest examples in the string:
Edward Lopera1ef6112004-08-09 16:14:41 +0000690 for m in self._EXAMPLE_RE.finditer(string.expandtabs()):
Edward Loper7c748462004-08-09 02:06:06 +0000691 # Add any text before this example, as a comment.
692 if m.start() > charnum:
Edward Lopera1ef6112004-08-09 16:14:41 +0000693 lines = string[charnum:m.start()-1].split('\n')
Edward Loper7c748462004-08-09 02:06:06 +0000694 output.extend([self._comment_line(l) for l in lines])
695 lineno += len(lines)
696
697 # Extract source/want from the regexp match.
Edward Loper74bca7a2004-08-12 02:27:44 +0000698 (source, want) = self._parse_example(m, name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000699 # Display the source
700 output.append(source)
701 # Display the expected output, if any
702 if want:
703 output.append('# Expected:')
Edward Lopera5db6002004-08-12 02:41:30 +0000704 output.extend(['## '+l for l in want.split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000705
706 # Update the line number & char number.
Edward Lopera1ef6112004-08-09 16:14:41 +0000707 lineno += string.count('\n', m.start(), m.end())
Edward Loper7c748462004-08-09 02:06:06 +0000708 charnum = m.end()
709 # Add any remaining text, as comments.
710 output.extend([self._comment_line(l)
Edward Lopera1ef6112004-08-09 16:14:41 +0000711 for l in string[charnum:].split('\n')])
Edward Loper7c748462004-08-09 02:06:06 +0000712 # Trim junk on both ends.
713 while output and output[-1] == '#':
714 output.pop()
715 while output and output[0] == '#':
716 output.pop(0)
717 # Combine the output, and return it.
718 return '\n'.join(output)
719
Edward Loper74bca7a2004-08-12 02:27:44 +0000720 def _parse_example(self, m, name, lineno):
721 """
722 Given a regular expression match from `_EXAMPLE_RE` (`m`),
723 return a pair `(source, want)`, where `source` is the matched
724 example's source code (with prompts and indentation stripped);
725 and `want` is the example's expected output (with indentation
726 stripped).
727
728 `name` is the string's name, and `lineno` is the line number
729 where the example starts; both are used for error messages.
730 """
Edward Loper7c748462004-08-09 02:06:06 +0000731 # Get the example's indentation level.
732 indent = len(m.group('indent'))
733
734 # Divide source into lines; check that they're properly
735 # indented; and then strip their indentation & prompts.
736 source_lines = m.group('source').split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000737 self._check_prompt_blank(source_lines, indent, name, lineno)
738 self._check_prefix(source_lines[1:], ' '*indent+'.', name, lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000739 source = '\n'.join([sl[indent+4:] for sl in source_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000740
741 # Divide want into lines; check that it's properly
742 # indented; and then strip the indentation.
Jim Fulton07a349c2004-08-22 14:10:00 +0000743 want = m.group('want')
744
745 # Strip trailing newline and following spaces
746 l = len(want.rstrip())
747 l = want.find('\n', l)
748 if l >= 0:
749 want = want[:l]
750
751 want_lines = want.split('\n')
Edward Lopera1ef6112004-08-09 16:14:41 +0000752 self._check_prefix(want_lines, ' '*indent, name,
Edward Loper7c748462004-08-09 02:06:06 +0000753 lineno+len(source_lines))
754 want = '\n'.join([wl[indent:] for wl in want_lines])
Edward Loper7c748462004-08-09 02:06:06 +0000755
756 return source, want
757
Edward Loper74bca7a2004-08-12 02:27:44 +0000758 # This regular expression looks for option directives in the
759 # source code of an example. Option directives are comments
760 # starting with "doctest:". Warning: this may give false
761 # positives for string-literals that contain the string
762 # "#doctest:". Eliminating these false positives would require
763 # actually parsing the string; but we limit them by ignoring any
764 # line containing "#doctest:" that is *followed* by a quote mark.
765 _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
766 re.MULTILINE)
767
768 def _find_options(self, source, name, lineno):
769 """
770 Return a dictionary containing option overrides extracted from
771 option directives in the given source string.
772
773 `name` is the string's name, and `lineno` is the line number
774 where the example starts; both are used for error messages.
775 """
776 options = {}
777 # (note: with the current regexp, this will match at most once:)
778 for m in self._OPTION_DIRECTIVE_RE.finditer(source):
779 option_strings = m.group(1).replace(',', ' ').split()
780 for option in option_strings:
781 if (option[0] not in '+-' or
782 option[1:] not in OPTIONFLAGS_BY_NAME):
783 raise ValueError('line %r of the doctest for %s '
784 'has an invalid option: %r' %
785 (lineno+1, name, option))
786 flag = OPTIONFLAGS_BY_NAME[option[1:]]
787 options[flag] = (option[0] == '+')
788 if options and self._IS_BLANK_OR_COMMENT(source):
789 raise ValueError('line %r of the doctest for %s has an option '
790 'directive on a line with no example: %r' %
791 (lineno, name, source))
792 return options
793
Edward Lopera5db6002004-08-12 02:41:30 +0000794 # This regular expression finds the indentation of every non-blank
795 # line in a string.
796 _INDENT_RE = re.compile('^([ ]+)(?=\S)', re.MULTILINE)
797
798 def _min_indent(self, s):
799 "Return the minimum indentation of any non-blank line in `s`"
800 return min([len(indent) for indent in self._INDENT_RE.findall(s)])
801
Edward Loper7c748462004-08-09 02:06:06 +0000802 def _comment_line(self, line):
Edward Loper74bca7a2004-08-12 02:27:44 +0000803 "Return a commented form of the given line"
Edward Loper7c748462004-08-09 02:06:06 +0000804 line = line.rstrip()
Tim Petersdd0e4752004-08-09 03:31:56 +0000805 if line:
Edward Lopera5db6002004-08-12 02:41:30 +0000806 return '# '+line
Tim Petersdd0e4752004-08-09 03:31:56 +0000807 else:
808 return '#'
Edward Loper7c748462004-08-09 02:06:06 +0000809
Edward Lopera1ef6112004-08-09 16:14:41 +0000810 def _check_prompt_blank(self, lines, indent, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000811 """
812 Given the lines of a source string (including prompts and
813 leading indentation), check to make sure that every prompt is
814 followed by a space character. If any line is not followed by
815 a space character, then raise ValueError.
816 """
Edward Loper7c748462004-08-09 02:06:06 +0000817 for i, line in enumerate(lines):
818 if len(line) >= indent+4 and line[indent+3] != ' ':
819 raise ValueError('line %r of the docstring for %s '
820 'lacks blank after %s: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000821 (lineno+i+1, name,
Edward Loper7c748462004-08-09 02:06:06 +0000822 line[indent:indent+3], line))
823
Edward Lopera1ef6112004-08-09 16:14:41 +0000824 def _check_prefix(self, lines, prefix, name, lineno):
Edward Loper74bca7a2004-08-12 02:27:44 +0000825 """
826 Check that every line in the given list starts with the given
827 prefix; if any line does not, then raise a ValueError.
828 """
Edward Loper7c748462004-08-09 02:06:06 +0000829 for i, line in enumerate(lines):
830 if line and not line.startswith(prefix):
831 raise ValueError('line %r of the docstring for %s has '
832 'inconsistent leading whitespace: %r' %
Edward Lopera1ef6112004-08-09 16:14:41 +0000833 (lineno+i+1, name, line))
Edward Loper7c748462004-08-09 02:06:06 +0000834
835
836######################################################################
837## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000838######################################################################
839
840class DocTestFinder:
841 """
842 A class used to extract the DocTests that are relevant to a given
843 object, from its docstring and the docstrings of its contained
844 objects. Doctests can currently be extracted from the following
845 object types: modules, functions, classes, methods, staticmethods,
846 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000847 """
848
Edward Lopera1ef6112004-08-09 16:14:41 +0000849 def __init__(self, verbose=False, parser=DocTestParser(),
Tim Petersf727c6c2004-08-08 01:48:59 +0000850 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000851 """
852 Create a new doctest finder.
853
Edward Lopera1ef6112004-08-09 16:14:41 +0000854 The optional argument `parser` specifies a class or
Tim Peters19397e52004-08-06 22:02:59 +0000855 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000856 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000857 signature for this factory function should match the signature
858 of the DocTest constructor.
859
Tim Peters8485b562004-08-04 18:46:34 +0000860 If the optional argument `recurse` is false, then `find` will
861 only examine the given object, and not any contained objects.
862 """
Edward Lopera1ef6112004-08-09 16:14:41 +0000863 self._parser = parser
Tim Peters8485b562004-08-04 18:46:34 +0000864 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000865 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000866 # _namefilter is undocumented, and exists only for temporary backward-
867 # compatibility support of testmod's deprecated isprivate mess.
868 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000869
870 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000871 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000872 """
873 Return a list of the DocTests that are defined by the given
874 object's docstring, or by any of its contained objects'
875 docstrings.
876
877 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000878 the given object. If the module is not specified or is None, then
879 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000880 correct module. The object's module is used:
881
882 - As a default namespace, if `globs` is not specified.
883 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000884 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000885 - To find the name of the file containing the object.
886 - To help find the line number of the object within its
887 file.
888
Tim Petersf3f57472004-08-08 06:11:48 +0000889 Contained objects whose module does not match `module` are ignored.
890
891 If `module` is False, no attempt to find the module will be made.
892 This is obscure, of use mostly in tests: if `module` is False, or
893 is None but cannot be found automatically, then all objects are
894 considered to belong to the (non-existent) module, so all contained
895 objects will (recursively) be searched for doctests.
896
Tim Peters8485b562004-08-04 18:46:34 +0000897 The globals for each DocTest is formed by combining `globs`
898 and `extraglobs` (bindings in `extraglobs` override bindings
899 in `globs`). A new copy of the globals dictionary is created
900 for each DocTest. If `globs` is not specified, then it
901 defaults to the module's `__dict__`, if specified, or {}
902 otherwise. If `extraglobs` is not specified, then it defaults
903 to {}.
904
Tim Peters8485b562004-08-04 18:46:34 +0000905 """
906 # If name was not specified, then extract it from the object.
907 if name is None:
908 name = getattr(obj, '__name__', None)
909 if name is None:
910 raise ValueError("DocTestFinder.find: name must be given "
911 "when obj.__name__ doesn't exist: %r" %
912 (type(obj),))
913
914 # Find the module that contains the given object (if obj is
915 # a module, then module=obj.). Note: this may fail, in which
916 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000917 if module is False:
918 module = None
919 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000920 module = inspect.getmodule(obj)
921
922 # Read the module's source code. This is used by
923 # DocTestFinder._find_lineno to find the line number for a
924 # given object's docstring.
925 try:
926 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
927 source_lines = linecache.getlines(file)
928 if not source_lines:
929 source_lines = None
930 except TypeError:
931 source_lines = None
932
933 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000934 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000935 if module is None:
936 globs = {}
937 else:
938 globs = module.__dict__.copy()
939 else:
940 globs = globs.copy()
941 if extraglobs is not None:
942 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000943
Tim Peters8485b562004-08-04 18:46:34 +0000944 # Recursively expore `obj`, extracting DocTests.
945 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000946 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000947 return tests
948
949 def _filter(self, obj, prefix, base):
950 """
951 Return true if the given object should not be examined.
952 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000953 return (self._namefilter is not None and
954 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000955
956 def _from_module(self, module, object):
957 """
958 Return true if the given object is defined in the given
959 module.
960 """
961 if module is None:
962 return True
963 elif inspect.isfunction(object):
964 return module.__dict__ is object.func_globals
965 elif inspect.isclass(object):
966 return module.__name__ == object.__module__
967 elif inspect.getmodule(object) is not None:
968 return module is inspect.getmodule(object)
969 elif hasattr(object, '__module__'):
970 return module.__name__ == object.__module__
971 elif isinstance(object, property):
972 return True # [XX] no way not be sure.
973 else:
974 raise ValueError("object must be a class or function")
975
Tim Petersf3f57472004-08-08 06:11:48 +0000976 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000977 """
978 Find tests for the given object and any contained objects, and
979 add them to `tests`.
980 """
981 if self._verbose:
982 print 'Finding tests in %s' % name
983
984 # If we've already processed this object, then ignore it.
985 if id(obj) in seen:
986 return
987 seen[id(obj)] = 1
988
989 # Find a test for this object, and add it to the list of tests.
990 test = self._get_test(obj, name, module, globs, source_lines)
991 if test is not None:
992 tests.append(test)
993
994 # Look for tests in a module's contained objects.
995 if inspect.ismodule(obj) and self._recurse:
996 for valname, val in obj.__dict__.items():
997 # Check if this contained object should be ignored.
998 if self._filter(val, name, valname):
999 continue
1000 valname = '%s.%s' % (name, valname)
1001 # Recurse to functions & classes.
1002 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +00001003 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001004 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001005 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001006
1007 # Look for tests in a module's __test__ dictionary.
1008 if inspect.ismodule(obj) and self._recurse:
1009 for valname, val in getattr(obj, '__test__', {}).items():
1010 if not isinstance(valname, basestring):
1011 raise ValueError("DocTestFinder.find: __test__ keys "
1012 "must be strings: %r" %
1013 (type(valname),))
1014 if not (inspect.isfunction(val) or inspect.isclass(val) or
1015 inspect.ismethod(val) or inspect.ismodule(val) or
1016 isinstance(val, basestring)):
1017 raise ValueError("DocTestFinder.find: __test__ values "
1018 "must be strings, functions, methods, "
1019 "classes, or modules: %r" %
1020 (type(val),))
1021 valname = '%s.%s' % (name, valname)
1022 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001023 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001024
1025 # Look for tests in a class's contained objects.
1026 if inspect.isclass(obj) and self._recurse:
1027 for valname, val in obj.__dict__.items():
1028 # Check if this contained object should be ignored.
1029 if self._filter(val, name, valname):
1030 continue
1031 # Special handling for staticmethod/classmethod.
1032 if isinstance(val, staticmethod):
1033 val = getattr(obj, valname)
1034 if isinstance(val, classmethod):
1035 val = getattr(obj, valname).im_func
1036
1037 # Recurse to methods, properties, and nested classes.
1038 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +00001039 isinstance(val, property)) and
1040 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +00001041 valname = '%s.%s' % (name, valname)
1042 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +00001043 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +00001044
1045 def _get_test(self, obj, name, module, globs, source_lines):
1046 """
1047 Return a DocTest for the given object, if it defines a docstring;
1048 otherwise, return None.
1049 """
1050 # Extract the object's docstring. If it doesn't have one,
1051 # then return None (no test for this object).
1052 if isinstance(obj, basestring):
1053 docstring = obj
1054 else:
1055 try:
1056 if obj.__doc__ is None:
1057 return None
1058 docstring = str(obj.__doc__)
1059 except (TypeError, AttributeError):
1060 return None
1061
1062 # Don't bother if the docstring is empty.
1063 if not docstring:
1064 return None
1065
1066 # Find the docstring's location in the file.
1067 lineno = self._find_lineno(obj, source_lines)
1068
1069 # Return a DocTest for this object.
1070 if module is None:
1071 filename = None
1072 else:
1073 filename = getattr(module, '__file__', module.__name__)
Jim Fulton07a349c2004-08-22 14:10:00 +00001074 if filename[-4:] in (".pyc", ".pyo"):
1075 filename = filename[:-1]
Edward Lopera1ef6112004-08-09 16:14:41 +00001076 return self._parser.get_doctest(docstring, globs, name,
1077 filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001078
1079 def _find_lineno(self, obj, source_lines):
1080 """
1081 Return a line number of the given object's docstring. Note:
1082 this method assumes that the object has a docstring.
1083 """
1084 lineno = None
1085
1086 # Find the line number for modules.
1087 if inspect.ismodule(obj):
1088 lineno = 0
1089
1090 # Find the line number for classes.
1091 # Note: this could be fooled if a class is defined multiple
1092 # times in a single file.
1093 if inspect.isclass(obj):
1094 if source_lines is None:
1095 return None
1096 pat = re.compile(r'^\s*class\s*%s\b' %
1097 getattr(obj, '__name__', '-'))
1098 for i, line in enumerate(source_lines):
1099 if pat.match(line):
1100 lineno = i
1101 break
1102
1103 # Find the line number for functions & methods.
1104 if inspect.ismethod(obj): obj = obj.im_func
1105 if inspect.isfunction(obj): obj = obj.func_code
1106 if inspect.istraceback(obj): obj = obj.tb_frame
1107 if inspect.isframe(obj): obj = obj.f_code
1108 if inspect.iscode(obj):
1109 lineno = getattr(obj, 'co_firstlineno', None)-1
1110
1111 # Find the line number where the docstring starts. Assume
1112 # that it's the first line that begins with a quote mark.
1113 # Note: this could be fooled by a multiline function
1114 # signature, where a continuation line begins with a quote
1115 # mark.
1116 if lineno is not None:
1117 if source_lines is None:
1118 return lineno+1
1119 pat = re.compile('(^|.*:)\s*\w*("|\')')
1120 for lineno in range(lineno, len(source_lines)):
1121 if pat.match(source_lines[lineno]):
1122 return lineno
1123
1124 # We couldn't find the line number.
1125 return None
1126
1127######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001128## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001129######################################################################
1130
Tim Peters8485b562004-08-04 18:46:34 +00001131class DocTestRunner:
1132 """
1133 A class used to run DocTest test cases, and accumulate statistics.
1134 The `run` method is used to process a single DocTest case. It
1135 returns a tuple `(f, t)`, where `t` is the number of test cases
1136 tried, and `f` is the number of test cases that failed.
1137
1138 >>> tests = DocTestFinder().find(_TestClass)
1139 >>> runner = DocTestRunner(verbose=False)
1140 >>> for test in tests:
1141 ... print runner.run(test)
1142 (0, 2)
1143 (0, 1)
1144 (0, 2)
1145 (0, 2)
1146
1147 The `summarize` method prints a summary of all the test cases that
1148 have been run by the runner, and returns an aggregated `(f, t)`
1149 tuple:
1150
1151 >>> runner.summarize(verbose=1)
1152 4 items passed all tests:
1153 2 tests in _TestClass
1154 2 tests in _TestClass.__init__
1155 2 tests in _TestClass.get
1156 1 tests in _TestClass.square
1157 7 tests in 4 items.
1158 7 passed and 0 failed.
1159 Test passed.
1160 (0, 7)
1161
1162 The aggregated number of tried examples and failed examples is
1163 also available via the `tries` and `failures` attributes:
1164
1165 >>> runner.tries
1166 7
1167 >>> runner.failures
1168 0
1169
1170 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001171 by an `OutputChecker`. This comparison may be customized with a
1172 number of option flags; see the documentation for `testmod` for
1173 more information. If the option flags are insufficient, then the
1174 comparison may also be customized by passing a subclass of
1175 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001176
1177 The test runner's display output can be controlled in two ways.
1178 First, an output function (`out) can be passed to
1179 `TestRunner.run`; this function will be called with strings that
1180 should be displayed. It defaults to `sys.stdout.write`. If
1181 capturing the output is not sufficient, then the display output
1182 can be also customized by subclassing DocTestRunner, and
1183 overriding the methods `report_start`, `report_success`,
1184 `report_unexpected_exception`, and `report_failure`.
1185 """
1186 # This divider string is used to separate failure messages, and to
1187 # separate sections of the summary.
1188 DIVIDER = "*" * 70
1189
Edward Loper34fcb142004-08-09 02:45:41 +00001190 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001191 """
1192 Create a new test runner.
1193
Edward Loper34fcb142004-08-09 02:45:41 +00001194 Optional keyword arg `checker` is the `OutputChecker` that
1195 should be used to compare the expected outputs and actual
1196 outputs of doctest examples.
1197
Tim Peters8485b562004-08-04 18:46:34 +00001198 Optional keyword arg 'verbose' prints lots of stuff if true,
1199 only failures if false; by default, it's true iff '-v' is in
1200 sys.argv.
1201
1202 Optional argument `optionflags` can be used to control how the
1203 test runner compares expected output to actual output, and how
1204 it displays failures. See the documentation for `testmod` for
1205 more information.
1206 """
Edward Loper34fcb142004-08-09 02:45:41 +00001207 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001208 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001209 verbose = '-v' in sys.argv
1210 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001211 self.optionflags = optionflags
Jim Fulton07a349c2004-08-22 14:10:00 +00001212 self.original_optionflags = optionflags
Tim Peters6ebe61f2003-06-27 20:48:05 +00001213
Tim Peters8485b562004-08-04 18:46:34 +00001214 # Keep track of the examples we've run.
1215 self.tries = 0
1216 self.failures = 0
1217 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001218
Tim Peters8485b562004-08-04 18:46:34 +00001219 # Create a fake output target for capturing doctest output.
1220 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001221
Tim Peters8485b562004-08-04 18:46:34 +00001222 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001223 # Reporting methods
1224 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001225
Tim Peters8485b562004-08-04 18:46:34 +00001226 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001227 """
Tim Peters8485b562004-08-04 18:46:34 +00001228 Report that the test runner is about to process the given
1229 example. (Only displays a message if verbose=True)
1230 """
1231 if self._verbose:
1232 out(_tag_msg("Trying", example.source) +
1233 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001234
Tim Peters8485b562004-08-04 18:46:34 +00001235 def report_success(self, out, test, example, got):
1236 """
1237 Report that the given example ran successfully. (Only
1238 displays a message if verbose=True)
1239 """
1240 if self._verbose:
1241 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001242
Tim Peters8485b562004-08-04 18:46:34 +00001243 def report_failure(self, out, test, example, got):
1244 """
1245 Report that the given example failed.
1246 """
1247 # Print an error message.
Edward Loper8e4a34b2004-08-12 02:34:27 +00001248 out(self._failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001249 self._checker.output_difference(example.want, got,
1250 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001251
Tim Peters8485b562004-08-04 18:46:34 +00001252 def report_unexpected_exception(self, out, test, example, exc_info):
1253 """
1254 Report that the given example raised an unexpected exception.
1255 """
Edward Loper8e4a34b2004-08-12 02:34:27 +00001256 out(self._failure_header(test, example) +
1257 _tag_msg("Exception raised", _exception_traceback(exc_info)))
Tim Peters7402f792001-10-02 03:53:41 +00001258
Edward Loper8e4a34b2004-08-12 02:34:27 +00001259 def _failure_header(self, test, example):
Jim Fulton07a349c2004-08-22 14:10:00 +00001260 out = [self.DIVIDER]
1261 if test.filename:
1262 if test.lineno is not None and example.lineno is not None:
1263 lineno = test.lineno + example.lineno + 1
1264 else:
1265 lineno = '?'
1266 out.append('File "%s", line %s, in %s' %
1267 (test.filename, lineno, test.name))
Tim Peters8485b562004-08-04 18:46:34 +00001268 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00001269 out.append('Line %s, in %s' % (example.lineno+1, test.name))
1270 out.append('Failed example:')
1271 source = example.source
1272 if source.endswith('\n'):
1273 source = source[:-1]
1274 out.append(' ' + '\n '.join(source.split('\n')))
1275 return '\n'.join(out)+'\n'
Tim Peters7402f792001-10-02 03:53:41 +00001276
Tim Peters8485b562004-08-04 18:46:34 +00001277 #/////////////////////////////////////////////////////////////////
1278 # DocTest Running
1279 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001280
Tim Peters8485b562004-08-04 18:46:34 +00001281 # A regular expression for handling `want` strings that contain
Tim Peters41a65ea2004-08-13 03:55:05 +00001282 # expected exceptions. It divides `want` into three pieces:
1283 # - the pre-exception output (`want`)
1284 # - the traceback header line (`hdr`)
1285 # - the exception message (`msg`), as generated by
1286 # traceback.format_exception_only()
1287 # `msg` may have multiple lines. We assume/require that the
1288 # exception message is the first non-indented line starting with a word
1289 # character following the traceback header line.
1290 _EXCEPTION_RE = re.compile(r"""
1291 (?P<want> .*?) # suck up everything until traceback header
1292 # Grab the traceback header. Different versions of Python have
1293 # said different things on the first traceback line.
1294 ^(?P<hdr> Traceback\ \(
1295 (?: most\ recent\ call\ last
1296 | innermost\ last
1297 ) \) :
1298 )
1299 \s* $ # toss trailing whitespace on traceback header
1300 .*? # don't blink: absorb stuff until a line *starts* with \w
1301 ^ (?P<msg> \w+ .*)
1302 """, re.VERBOSE | re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001303
Tim Peters8485b562004-08-04 18:46:34 +00001304 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001305 """
Tim Peters8485b562004-08-04 18:46:34 +00001306 Run the examples in `test`. Write the outcome of each example
1307 with one of the `DocTestRunner.report_*` methods, using the
1308 writer function `out`. `compileflags` is the set of compiler
1309 flags that should be used to execute examples. Return a tuple
1310 `(f, t)`, where `t` is the number of examples tried, and `f`
1311 is the number of examples that failed. The examples are run
1312 in the namespace `test.globs`.
1313 """
1314 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001315 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001316
1317 # Save the option flags (since option directives can be used
1318 # to modify them).
1319 original_optionflags = self.optionflags
1320
1321 # Process each example.
1322 for example in test.examples:
Edward Loper74bca7a2004-08-12 02:27:44 +00001323 # Merge in the example's options.
1324 self.optionflags = original_optionflags
1325 if example.options:
1326 for (optionflag, val) in example.options.items():
1327 if val:
1328 self.optionflags |= optionflag
1329 else:
1330 self.optionflags &= ~optionflag
Tim Peters8485b562004-08-04 18:46:34 +00001331
1332 # Record that we started this example.
1333 tries += 1
1334 self.report_start(out, test, example)
1335
1336 # Run the example in the given context (globs), and record
1337 # any exception that gets raised. (But don't intercept
1338 # keyboard interrupts.)
1339 try:
Tim Peters208ca702004-08-09 04:12:36 +00001340 # Don't blink! This is where the user's code gets run.
Tim Petersbb431472004-08-09 03:51:46 +00001341 exec compile(example.source, "<string>", "single",
Tim Peters8485b562004-08-04 18:46:34 +00001342 compileflags, 1) in test.globs
1343 exception = None
1344 except KeyboardInterrupt:
1345 raise
1346 except:
1347 exception = sys.exc_info()
1348
Tim Peters208ca702004-08-09 04:12:36 +00001349 got = self._fakeout.getvalue() # the actual output
Tim Peters8485b562004-08-04 18:46:34 +00001350 self._fakeout.truncate(0)
1351
1352 # If the example executed without raising any exceptions,
1353 # then verify its output and report its outcome.
1354 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001355 if self._checker.check_output(example.want, got,
1356 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001357 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001358 else:
Tim Peters8485b562004-08-04 18:46:34 +00001359 self.report_failure(out, test, example, got)
1360 failures += 1
1361
1362 # If the example raised an exception, then check if it was
1363 # expected.
1364 else:
1365 exc_info = sys.exc_info()
1366 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1367
1368 # Search the `want` string for an exception. If we don't
1369 # find one, then report an unexpected exception.
1370 m = self._EXCEPTION_RE.match(example.want)
1371 if m is None:
1372 self.report_unexpected_exception(out, test, example,
1373 exc_info)
1374 failures += 1
1375 else:
Tim Peters41a65ea2004-08-13 03:55:05 +00001376 e_want, e_msg = m.group('want', 'msg')
Tim Peters8485b562004-08-04 18:46:34 +00001377 # The test passes iff the pre-exception output and
1378 # the exception description match the values given
1379 # in `want`.
Tim Peters41a65ea2004-08-13 03:55:05 +00001380 if (self._checker.check_output(e_want, got,
Edward Loper34fcb142004-08-09 02:45:41 +00001381 self.optionflags) and
Tim Peters41a65ea2004-08-13 03:55:05 +00001382 self._checker.check_output(e_msg, exc_msg,
Edward Loper34fcb142004-08-09 02:45:41 +00001383 self.optionflags)):
Tim Peters8485b562004-08-04 18:46:34 +00001384 self.report_success(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001385 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001386 else:
1387 self.report_failure(out, test, example,
Tim Peters41a65ea2004-08-13 03:55:05 +00001388 got + _exception_traceback(exc_info))
Tim Peters8485b562004-08-04 18:46:34 +00001389 failures += 1
1390
1391 # Restore the option flags (in case they were modified)
1392 self.optionflags = original_optionflags
1393
1394 # Record and return the number of failures and tries.
1395 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001396 return failures, tries
1397
Tim Peters8485b562004-08-04 18:46:34 +00001398 def __record_outcome(self, test, f, t):
1399 """
1400 Record the fact that the given DocTest (`test`) generated `f`
1401 failures out of `t` tried examples.
1402 """
1403 f2, t2 = self._name2ft.get(test.name, (0,0))
1404 self._name2ft[test.name] = (f+f2, t+t2)
1405 self.failures += f
1406 self.tries += t
1407
1408 def run(self, test, compileflags=None, out=None, clear_globs=True):
1409 """
1410 Run the examples in `test`, and display the results using the
1411 writer function `out`.
1412
1413 The examples are run in the namespace `test.globs`. If
1414 `clear_globs` is true (the default), then this namespace will
1415 be cleared after the test runs, to help with garbage
1416 collection. If you would like to examine the namespace after
1417 the test completes, then use `clear_globs=False`.
1418
1419 `compileflags` gives the set of flags that should be used by
1420 the Python compiler when running the examples. If not
1421 specified, then it will default to the set of future-import
1422 flags that apply to `globs`.
1423
1424 The output of each example is checked using
1425 `DocTestRunner.check_output`, and the results are formatted by
1426 the `DocTestRunner.report_*` methods.
1427 """
1428 if compileflags is None:
1429 compileflags = _extract_future_flags(test.globs)
Jim Fulton356fd192004-08-09 11:34:47 +00001430
Tim Peters6c542b72004-08-09 16:43:36 +00001431 save_stdout = sys.stdout
Tim Peters8485b562004-08-04 18:46:34 +00001432 if out is None:
Tim Peters6c542b72004-08-09 16:43:36 +00001433 out = save_stdout.write
1434 sys.stdout = self._fakeout
Tim Peters8485b562004-08-04 18:46:34 +00001435
Tim Peters6c542b72004-08-09 16:43:36 +00001436 # Patch pdb.set_trace to restore sys.stdout, so that interactive
1437 # debugging output is visible (not still redirected to self._fakeout).
1438 # Note that we run "the real" pdb.set_trace (captured at doctest
1439 # import time) in our replacement. Because the current run() may
1440 # run another doctest (and so on), the current pdb.set_trace may be
1441 # our set_trace function, which changes sys.stdout. If we called
1442 # a chain of those, we wouldn't be left with the save_stdout
1443 # *this* run() invocation wants.
Jim Fulton356fd192004-08-09 11:34:47 +00001444 def set_trace():
Tim Peters6c542b72004-08-09 16:43:36 +00001445 sys.stdout = save_stdout
Jim Fulton356fd192004-08-09 11:34:47 +00001446 real_pdb_set_trace()
1447
Tim Peters6c542b72004-08-09 16:43:36 +00001448 save_set_trace = pdb.set_trace
1449 pdb.set_trace = set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001450 try:
Tim Peters8485b562004-08-04 18:46:34 +00001451 return self.__run(test, compileflags, out)
1452 finally:
Tim Peters6c542b72004-08-09 16:43:36 +00001453 sys.stdout = save_stdout
1454 pdb.set_trace = save_set_trace
Tim Peters8485b562004-08-04 18:46:34 +00001455 if clear_globs:
1456 test.globs.clear()
1457
1458 #/////////////////////////////////////////////////////////////////
1459 # Summarization
1460 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001461 def summarize(self, verbose=None):
1462 """
Tim Peters8485b562004-08-04 18:46:34 +00001463 Print a summary of all the test cases that have been run by
1464 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1465 the total number of failed examples, and `t` is the total
1466 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001467
Tim Peters8485b562004-08-04 18:46:34 +00001468 The optional `verbose` argument controls how detailed the
1469 summary is. If the verbosity is not specified, then the
1470 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001471 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001472 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001473 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001474 notests = []
1475 passed = []
1476 failed = []
1477 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001478 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001479 name, (f, t) = x
1480 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001481 totalt += t
1482 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001483 if t == 0:
1484 notests.append(name)
1485 elif f == 0:
1486 passed.append( (name, t) )
1487 else:
1488 failed.append(x)
1489 if verbose:
1490 if notests:
1491 print len(notests), "items had no tests:"
1492 notests.sort()
1493 for thing in notests:
1494 print " ", thing
1495 if passed:
1496 print len(passed), "items passed all tests:"
1497 passed.sort()
1498 for thing, count in passed:
1499 print " %3d tests in %s" % (count, thing)
1500 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001501 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001502 print len(failed), "items had failures:"
1503 failed.sort()
1504 for thing, (f, t) in failed:
1505 print " %3d of %3d in %s" % (f, t, thing)
1506 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001507 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001508 print totalt - totalf, "passed and", totalf, "failed."
1509 if totalf:
1510 print "***Test Failed***", totalf, "failures."
1511 elif verbose:
1512 print "Test passed."
1513 return totalf, totalt
1514
Edward Loper34fcb142004-08-09 02:45:41 +00001515class OutputChecker:
1516 """
1517 A class used to check the whether the actual output from a doctest
1518 example matches the expected output. `OutputChecker` defines two
1519 methods: `check_output`, which compares a given pair of outputs,
1520 and returns true if they match; and `output_difference`, which
1521 returns a string describing the differences between two outputs.
1522 """
1523 def check_output(self, want, got, optionflags):
1524 """
Edward Loper74bca7a2004-08-12 02:27:44 +00001525 Return True iff the actual output from an example (`got`)
1526 matches the expected output (`want`). These strings are
1527 always considered to match if they are identical; but
1528 depending on what option flags the test runner is using,
1529 several non-exact match types are also possible. See the
1530 documentation for `TestRunner` for more information about
1531 option flags.
Edward Loper34fcb142004-08-09 02:45:41 +00001532 """
1533 # Handle the common case first, for efficiency:
1534 # if they're string-identical, always return true.
1535 if got == want:
1536 return True
1537
1538 # The values True and False replaced 1 and 0 as the return
1539 # value for boolean comparisons in Python 2.3.
1540 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1541 if (got,want) == ("True\n", "1\n"):
1542 return True
1543 if (got,want) == ("False\n", "0\n"):
1544 return True
1545
1546 # <BLANKLINE> can be used as a special sequence to signify a
1547 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1548 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1549 # Replace <BLANKLINE> in want with a blank line.
1550 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1551 '', want)
1552 # If a line in got contains only spaces, then remove the
1553 # spaces.
1554 got = re.sub('(?m)^\s*?$', '', got)
1555 if got == want:
1556 return True
1557
1558 # This flag causes doctest to ignore any differences in the
1559 # contents of whitespace strings. Note that this can be used
1560 # in conjunction with the ELLISPIS flag.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001561 if optionflags & NORMALIZE_WHITESPACE:
Edward Loper34fcb142004-08-09 02:45:41 +00001562 got = ' '.join(got.split())
1563 want = ' '.join(want.split())
1564 if got == want:
1565 return True
1566
1567 # The ELLIPSIS flag says to let the sequence "..." in `want`
Tim Peters26b3ebb2004-08-19 08:10:08 +00001568 # match any substring in `got`.
Tim Peters1cf3aa62004-08-19 06:49:33 +00001569 if optionflags & ELLIPSIS:
Tim Petersb0a04e12004-08-20 02:08:04 +00001570 if _ellipsis_match(want, got):
Edward Loper34fcb142004-08-09 02:45:41 +00001571 return True
1572
1573 # We didn't find any match; return false.
1574 return False
1575
1576 def output_difference(self, want, got, optionflags):
1577 """
1578 Return a string describing the differences between the
Edward Loper74bca7a2004-08-12 02:27:44 +00001579 expected output for an example (`want`) and the actual output
1580 (`got`). `optionflags` is the set of option flags used to
1581 compare `want` and `got`. `indent` is the indentation of the
1582 original example.
Edward Loper34fcb142004-08-09 02:45:41 +00001583 """
Jim Fulton07a349c2004-08-22 14:10:00 +00001584
Edward Loper68ba9a62004-08-12 02:43:49 +00001585 # If <BLANKLINE>s are being used, then replace blank lines
1586 # with <BLANKLINE> in the actual output string.
Edward Loper34fcb142004-08-09 02:45:41 +00001587 if not (optionflags & DONT_ACCEPT_BLANKLINE):
Edward Loper68ba9a62004-08-12 02:43:49 +00001588 got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001589
1590 # Check if we should use diff. Don't use diff if the actual
1591 # or expected outputs are too short, or if the expected output
1592 # contains an ellipsis marker.
1593 if ((optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and
1594 want.count('\n') > 2 and got.count('\n') > 2 and
1595 not (optionflags & ELLIPSIS and '...' in want)):
1596 # Split want & got into lines.
1597 want_lines = [l+'\n' for l in want.split('\n')]
1598 got_lines = [l+'\n' for l in got.split('\n')]
1599 # Use difflib to find their differences.
1600 if optionflags & UNIFIED_DIFF:
1601 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1602 fromfile='Expected', tofile='Got')
1603 kind = 'unified'
1604 elif optionflags & CONTEXT_DIFF:
1605 diff = difflib.context_diff(want_lines, got_lines, n=2,
1606 fromfile='Expected', tofile='Got')
1607 kind = 'context'
1608 else:
1609 assert 0, 'Bad diff option'
1610 # Remove trailing whitespace on diff output.
1611 diff = [line.rstrip() + '\n' for line in diff]
1612 return _tag_msg("Differences (" + kind + " diff)",
1613 ''.join(diff))
1614
1615 # If we're not using diff, then simply list the expected
1616 # output followed by the actual output.
Jim Fulton07a349c2004-08-22 14:10:00 +00001617 if want.endswith('\n'):
1618 want = want[:-1]
1619 want = ' ' + '\n '.join(want.split('\n'))
1620 if got.endswith('\n'):
1621 got = got[:-1]
1622 got = ' ' + '\n '.join(got.split('\n'))
1623 return "Expected:\n%s\nGot:\n%s\n" % (want, got)
Edward Loper34fcb142004-08-09 02:45:41 +00001624
Tim Peters19397e52004-08-06 22:02:59 +00001625class DocTestFailure(Exception):
1626 """A DocTest example has failed in debugging mode.
1627
1628 The exception instance has variables:
1629
1630 - test: the DocTest object being run
1631
1632 - excample: the Example object that failed
1633
1634 - got: the actual output
1635 """
1636 def __init__(self, test, example, got):
1637 self.test = test
1638 self.example = example
1639 self.got = got
1640
1641 def __str__(self):
1642 return str(self.test)
1643
1644class UnexpectedException(Exception):
1645 """A DocTest example has encountered an unexpected exception
1646
1647 The exception instance has variables:
1648
1649 - test: the DocTest object being run
1650
1651 - excample: the Example object that failed
1652
1653 - exc_info: the exception info
1654 """
1655 def __init__(self, test, example, exc_info):
1656 self.test = test
1657 self.example = example
1658 self.exc_info = exc_info
1659
1660 def __str__(self):
1661 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001662
Tim Peters19397e52004-08-06 22:02:59 +00001663class DebugRunner(DocTestRunner):
1664 r"""Run doc tests but raise an exception as soon as there is a failure.
1665
1666 If an unexpected exception occurs, an UnexpectedException is raised.
1667 It contains the test, the example, and the original exception:
1668
1669 >>> runner = DebugRunner(verbose=False)
Edward Lopera1ef6112004-08-09 16:14:41 +00001670 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
1671 ... {}, 'foo', 'foo.py', 0)
Tim Peters19397e52004-08-06 22:02:59 +00001672 >>> try:
1673 ... runner.run(test)
1674 ... except UnexpectedException, failure:
1675 ... pass
1676
1677 >>> failure.test is test
1678 True
1679
1680 >>> failure.example.want
1681 '42\n'
1682
1683 >>> exc_info = failure.exc_info
1684 >>> raise exc_info[0], exc_info[1], exc_info[2]
1685 Traceback (most recent call last):
1686 ...
1687 KeyError
1688
1689 We wrap the original exception to give the calling application
1690 access to the test and example information.
1691
1692 If the output doesn't match, then a DocTestFailure is raised:
1693
Edward Lopera1ef6112004-08-09 16:14:41 +00001694 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001695 ... >>> x = 1
1696 ... >>> x
1697 ... 2
1698 ... ''', {}, 'foo', 'foo.py', 0)
1699
1700 >>> try:
1701 ... runner.run(test)
1702 ... except DocTestFailure, failure:
1703 ... pass
1704
1705 DocTestFailure objects provide access to the test:
1706
1707 >>> failure.test is test
1708 True
1709
1710 As well as to the example:
1711
1712 >>> failure.example.want
1713 '2\n'
1714
1715 and the actual output:
1716
1717 >>> failure.got
1718 '1\n'
1719
1720 If a failure or error occurs, the globals are left intact:
1721
1722 >>> del test.globs['__builtins__']
1723 >>> test.globs
1724 {'x': 1}
1725
Edward Lopera1ef6112004-08-09 16:14:41 +00001726 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001727 ... >>> x = 2
1728 ... >>> raise KeyError
1729 ... ''', {}, 'foo', 'foo.py', 0)
1730
1731 >>> runner.run(test)
1732 Traceback (most recent call last):
1733 ...
1734 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001735
Tim Peters19397e52004-08-06 22:02:59 +00001736 >>> del test.globs['__builtins__']
1737 >>> test.globs
1738 {'x': 2}
1739
1740 But the globals are cleared if there is no error:
1741
Edward Lopera1ef6112004-08-09 16:14:41 +00001742 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00001743 ... >>> x = 2
1744 ... ''', {}, 'foo', 'foo.py', 0)
1745
1746 >>> runner.run(test)
1747 (0, 1)
1748
1749 >>> test.globs
1750 {}
1751
1752 """
1753
1754 def run(self, test, compileflags=None, out=None, clear_globs=True):
1755 r = DocTestRunner.run(self, test, compileflags, out, False)
1756 if clear_globs:
1757 test.globs.clear()
1758 return r
1759
1760 def report_unexpected_exception(self, out, test, example, exc_info):
1761 raise UnexpectedException(test, example, exc_info)
1762
1763 def report_failure(self, out, test, example, got):
1764 raise DocTestFailure(test, example, got)
1765
Tim Peters8485b562004-08-04 18:46:34 +00001766######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001767## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001768######################################################################
1769# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001770
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001771def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001772 report=True, optionflags=0, extraglobs=None,
1773 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001774 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001775 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001776
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001777 Test examples in docstrings in functions and classes reachable
1778 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001779 with m.__doc__. Unless isprivate is specified, private names
1780 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001781
1782 Also test examples reachable from dict m.__test__ if it exists and is
Tim Petersc2388a22004-08-10 01:41:28 +00001783 not None. m.__test__ maps names to functions, classes and strings;
Tim Peters8a7d2d52001-01-16 07:10:57 +00001784 function and class docstrings are tested even if the name is private;
1785 strings are tested directly, as if they were docstrings.
1786
1787 Return (#failures, #tests).
1788
1789 See doctest.__doc__ for an overview.
1790
1791 Optional keyword arg "name" gives the name of the module; by default
1792 use m.__name__.
1793
1794 Optional keyword arg "globs" gives a dict to be used as the globals
1795 when executing examples; by default, use m.__dict__. A copy of this
1796 dict is actually used for each docstring, so that each docstring's
1797 examples start with a clean slate.
1798
Tim Peters8485b562004-08-04 18:46:34 +00001799 Optional keyword arg "extraglobs" gives a dictionary that should be
1800 merged into the globals that are used to execute examples. By
1801 default, no extra globals are used. This is new in 2.4.
1802
Tim Peters8a7d2d52001-01-16 07:10:57 +00001803 Optional keyword arg "verbose" prints lots of stuff if true, prints
1804 only failures if false; by default, it's true iff "-v" is in sys.argv.
1805
Tim Peters8a7d2d52001-01-16 07:10:57 +00001806 Optional keyword arg "report" prints a summary at the end when true,
1807 else prints nothing at the end. In verbose mode, the summary is
1808 detailed, else very brief (in fact, empty if all tests passed).
1809
Tim Peters6ebe61f2003-06-27 20:48:05 +00001810 Optional keyword arg "optionflags" or's together module constants,
1811 and defaults to 0. This is new in 2.3. Possible values:
1812
1813 DONT_ACCEPT_TRUE_FOR_1
1814 By default, if an expected output block contains just "1",
1815 an actual output block containing just "True" is considered
1816 to be a match, and similarly for "0" versus "False". When
1817 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1818 is allowed.
1819
Tim Peters8485b562004-08-04 18:46:34 +00001820 DONT_ACCEPT_BLANKLINE
1821 By default, if an expected output block contains a line
1822 containing only the string "<BLANKLINE>", then that line
1823 will match a blank line in the actual output. When
1824 DONT_ACCEPT_BLANKLINE is specified, this substitution is
1825 not allowed.
1826
1827 NORMALIZE_WHITESPACE
1828 When NORMALIZE_WHITESPACE is specified, all sequences of
1829 whitespace are treated as equal. I.e., any sequence of
1830 whitespace within the expected output will match any
1831 sequence of whitespace within the actual output.
1832
1833 ELLIPSIS
1834 When ELLIPSIS is specified, then an ellipsis marker
1835 ("...") in the expected output can match any substring in
1836 the actual output.
1837
1838 UNIFIED_DIFF
1839 When UNIFIED_DIFF is specified, failures that involve
1840 multi-line expected and actual outputs will be displayed
1841 using a unified diff.
1842
1843 CONTEXT_DIFF
1844 When CONTEXT_DIFF is specified, failures that involve
1845 multi-line expected and actual outputs will be displayed
1846 using a context diff.
Tim Peters19397e52004-08-06 22:02:59 +00001847
1848 Optional keyword arg "raise_on_error" raises an exception on the
1849 first unexpected exception or failure. This allows failures to be
1850 post-mortem debugged.
1851
Tim Petersf727c6c2004-08-08 01:48:59 +00001852 Deprecated in Python 2.4:
1853 Optional keyword arg "isprivate" specifies a function used to
1854 determine whether a name is private. The default function is
1855 treat all functions as public. Optionally, "isprivate" can be
1856 set to doctest.is_private to skip over functions marked as private
1857 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001858 """
1859
1860 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001861 Advanced tomfoolery: testmod runs methods of a local instance of
1862 class doctest.Tester, then merges the results into (or creates)
1863 global Tester instance doctest.master. Methods of doctest.master
1864 can be called directly too, if you want to do something unusual.
1865 Passing report=0 to testmod is especially useful then, to delay
1866 displaying a summary. Invoke doctest.master.summarize(verbose)
1867 when you're done fiddling.
1868 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001869 if isprivate is not None:
1870 warnings.warn("the isprivate argument is deprecated; "
1871 "examine DocTestFinder.find() lists instead",
1872 DeprecationWarning)
1873
Tim Peters8485b562004-08-04 18:46:34 +00001874 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001875 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001876 # DWA - m will still be None if this wasn't invoked from the command
1877 # line, in which case the following TypeError is about as good an error
1878 # as we should expect
1879 m = sys.modules.get('__main__')
1880
Tim Peters8485b562004-08-04 18:46:34 +00001881 # Check that we were actually given a module.
1882 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001883 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001884
1885 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001886 if name is None:
1887 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001888
1889 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001890 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001891
1892 if raise_on_error:
1893 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1894 else:
1895 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1896
Tim Peters8485b562004-08-04 18:46:34 +00001897 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1898 runner.run(test)
1899
Tim Peters8a7d2d52001-01-16 07:10:57 +00001900 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001901 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001902
Tim Peters8485b562004-08-04 18:46:34 +00001903 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001904
Tim Peters8485b562004-08-04 18:46:34 +00001905def run_docstring_examples(f, globs, verbose=False, name="NoName",
1906 compileflags=None, optionflags=0):
1907 """
1908 Test examples in the given object's docstring (`f`), using `globs`
1909 as globals. Optional argument `name` is used in failure messages.
1910 If the optional argument `verbose` is true, then generate output
1911 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001912
Tim Peters8485b562004-08-04 18:46:34 +00001913 `compileflags` gives the set of flags that should be used by the
1914 Python compiler when running the examples. If not specified, then
1915 it will default to the set of future-import flags that apply to
1916 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001917
Tim Peters8485b562004-08-04 18:46:34 +00001918 Optional keyword arg `optionflags` specifies options for the
1919 testing and output. See the documentation for `testmod` for more
1920 information.
1921 """
1922 # Find, parse, and run all tests in the given module.
1923 finder = DocTestFinder(verbose=verbose, recurse=False)
1924 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1925 for test in finder.find(f, name, globs=globs):
1926 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001927
Tim Peters8485b562004-08-04 18:46:34 +00001928######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001929## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001930######################################################################
1931# This is provided only for backwards compatibility. It's not
1932# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001933
Tim Peters8485b562004-08-04 18:46:34 +00001934class Tester:
1935 def __init__(self, mod=None, globs=None, verbose=None,
1936 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001937
1938 warnings.warn("class Tester is deprecated; "
1939 "use class doctest.DocTestRunner instead",
1940 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001941 if mod is None and globs is None:
1942 raise TypeError("Tester.__init__: must specify mod or globs")
1943 if mod is not None and not _ismodule(mod):
1944 raise TypeError("Tester.__init__: mod must be a module; %r" %
1945 (mod,))
1946 if globs is None:
1947 globs = mod.__dict__
1948 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001949
Tim Peters8485b562004-08-04 18:46:34 +00001950 self.verbose = verbose
1951 self.isprivate = isprivate
1952 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001953 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001954 self.testrunner = DocTestRunner(verbose=verbose,
1955 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001956
Tim Peters8485b562004-08-04 18:46:34 +00001957 def runstring(self, s, name):
Edward Lopera1ef6112004-08-09 16:14:41 +00001958 test = DocTestParser().get_doctest(s, self.globs, name, None, None)
Tim Peters8485b562004-08-04 18:46:34 +00001959 if self.verbose:
1960 print "Running string", name
1961 (f,t) = self.testrunner.run(test)
1962 if self.verbose:
1963 print f, "of", t, "examples failed in string", name
1964 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001965
Tim Petersf3f57472004-08-08 06:11:48 +00001966 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001967 f = t = 0
1968 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001969 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001970 for test in tests:
1971 (f2, t2) = self.testrunner.run(test)
1972 (f,t) = (f+f2, t+t2)
1973 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001974
Tim Peters8485b562004-08-04 18:46:34 +00001975 def rundict(self, d, name, module=None):
1976 import new
1977 m = new.module(name)
1978 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001979 if module is None:
1980 module = False
1981 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001982
Tim Peters8485b562004-08-04 18:46:34 +00001983 def run__test__(self, d, name):
1984 import new
1985 m = new.module(name)
1986 m.__test__ = d
1987 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001988
Tim Peters8485b562004-08-04 18:46:34 +00001989 def summarize(self, verbose=None):
1990 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001991
Tim Peters8485b562004-08-04 18:46:34 +00001992 def merge(self, other):
1993 d = self.testrunner._name2ft
1994 for name, (f, t) in other.testrunner._name2ft.items():
1995 if name in d:
1996 print "*** Tester.merge: '" + name + "' in both" \
1997 " testers; summing outcomes."
1998 f2, t2 = d[name]
1999 f = f + f2
2000 t = t + t2
2001 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00002002
Tim Peters8485b562004-08-04 18:46:34 +00002003######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002004## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00002005######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00002006
Tim Peters19397e52004-08-06 22:02:59 +00002007class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00002008
Edward Loper34fcb142004-08-09 02:45:41 +00002009 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
2010 checker=None):
Jim Fulton07a349c2004-08-22 14:10:00 +00002011
Jim Fultona643b652004-07-14 19:06:50 +00002012 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00002013 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00002014 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00002015 self._dt_test = test
2016 self._dt_setUp = setUp
2017 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00002018
Jim Fultona643b652004-07-14 19:06:50 +00002019 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00002020 if self._dt_setUp is not None:
2021 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00002022
2023 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00002024 if self._dt_tearDown is not None:
2025 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00002026
2027 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00002028 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00002029 old = sys.stdout
2030 new = StringIO()
Edward Loper34fcb142004-08-09 02:45:41 +00002031 runner = DocTestRunner(optionflags=self._dt_optionflags,
2032 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002033
Jim Fultona643b652004-07-14 19:06:50 +00002034 try:
Tim Peters19397e52004-08-06 22:02:59 +00002035 runner.DIVIDER = "-"*70
2036 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00002037 finally:
2038 sys.stdout = old
2039
2040 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00002041 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00002042
Tim Peters19397e52004-08-06 22:02:59 +00002043 def format_failure(self, err):
2044 test = self._dt_test
2045 if test.lineno is None:
2046 lineno = 'unknown line number'
2047 else:
Jim Fulton07a349c2004-08-22 14:10:00 +00002048 lineno = '%s' % test.lineno
Tim Peters19397e52004-08-06 22:02:59 +00002049 lname = '.'.join(test.name.split('.')[-1:])
2050 return ('Failed doctest test for %s\n'
2051 ' File "%s", line %s, in %s\n\n%s'
2052 % (test.name, test.filename, lineno, lname, err)
2053 )
2054
2055 def debug(self):
2056 r"""Run the test case without results and without catching exceptions
2057
2058 The unit test framework includes a debug method on test cases
2059 and test suites to support post-mortem debugging. The test code
2060 is run in such a way that errors are not caught. This way a
2061 caller can catch the errors and initiate post-mortem debugging.
2062
2063 The DocTestCase provides a debug method that raises
2064 UnexpectedException errors if there is an unexepcted
2065 exception:
2066
Edward Lopera1ef6112004-08-09 16:14:41 +00002067 >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
Tim Peters19397e52004-08-06 22:02:59 +00002068 ... {}, 'foo', 'foo.py', 0)
2069 >>> case = DocTestCase(test)
2070 >>> try:
2071 ... case.debug()
2072 ... except UnexpectedException, failure:
2073 ... pass
2074
2075 The UnexpectedException contains the test, the example, and
2076 the original exception:
2077
2078 >>> failure.test is test
2079 True
2080
2081 >>> failure.example.want
2082 '42\n'
2083
2084 >>> exc_info = failure.exc_info
2085 >>> raise exc_info[0], exc_info[1], exc_info[2]
2086 Traceback (most recent call last):
2087 ...
2088 KeyError
2089
2090 If the output doesn't match, then a DocTestFailure is raised:
2091
Edward Lopera1ef6112004-08-09 16:14:41 +00002092 >>> test = DocTestParser().get_doctest('''
Tim Peters19397e52004-08-06 22:02:59 +00002093 ... >>> x = 1
2094 ... >>> x
2095 ... 2
2096 ... ''', {}, 'foo', 'foo.py', 0)
2097 >>> case = DocTestCase(test)
2098
2099 >>> try:
2100 ... case.debug()
2101 ... except DocTestFailure, failure:
2102 ... pass
2103
2104 DocTestFailure objects provide access to the test:
2105
2106 >>> failure.test is test
2107 True
2108
2109 As well as to the example:
2110
2111 >>> failure.example.want
2112 '2\n'
2113
2114 and the actual output:
2115
2116 >>> failure.got
2117 '1\n'
2118
2119 """
2120
Edward Loper34fcb142004-08-09 02:45:41 +00002121 runner = DebugRunner(optionflags=self._dt_optionflags,
2122 checker=self._dt_checker, verbose=False)
Edward Loper3a3817f2004-08-19 19:26:06 +00002123 runner.run(self._dt_test)
Jim Fultona643b652004-07-14 19:06:50 +00002124
2125 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002126 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002127
2128 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002129 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002130 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2131
2132 __str__ = __repr__
2133
2134 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002135 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002136
Tim Peters19397e52004-08-06 22:02:59 +00002137def DocTestSuite(module=None, globs=None, extraglobs=None,
2138 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002139 setUp=lambda: None, tearDown=lambda: None,
2140 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002141 """
Tim Peters19397e52004-08-06 22:02:59 +00002142 Convert doctest tests for a mudule to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002143
Tim Peters19397e52004-08-06 22:02:59 +00002144 This converts each documentation string in a module that
2145 contains doctest tests to a unittest test case. If any of the
2146 tests in a doc string fail, then the test case fails. An exception
2147 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002148 (sometimes approximate) line number.
2149
Tim Peters19397e52004-08-06 22:02:59 +00002150 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002151 can be either a module or a module name.
2152
2153 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002154 """
Jim Fultona643b652004-07-14 19:06:50 +00002155
Tim Peters8485b562004-08-04 18:46:34 +00002156 if test_finder is None:
2157 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002158
Tim Peters19397e52004-08-06 22:02:59 +00002159 module = _normalize_module(module)
2160 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2161 if globs is None:
2162 globs = module.__dict__
2163 if not tests: # [XX] why do we want to do this?
2164 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002165
2166 tests.sort()
2167 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002168 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002169 if len(test.examples) == 0:
2170 continue
Tim Peters8485b562004-08-04 18:46:34 +00002171 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002172 filename = module.__file__
Jim Fulton07a349c2004-08-22 14:10:00 +00002173 if filename[-4:] in (".pyc", ".pyo"):
Tim Petersdb3756d2003-06-29 05:30:48 +00002174 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002175 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002176 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2177 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002178
2179 return suite
2180
2181class DocFileCase(DocTestCase):
2182
2183 def id(self):
2184 return '_'.join(self._dt_test.name.split('.'))
2185
2186 def __repr__(self):
2187 return self._dt_test.filename
2188 __str__ = __repr__
2189
2190 def format_failure(self, err):
2191 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2192 % (self._dt_test.name, self._dt_test.filename, err)
2193 )
2194
2195def DocFileTest(path, package=None, globs=None,
2196 setUp=None, tearDown=None,
2197 optionflags=0):
2198 package = _normalize_module(package)
2199 name = path.split('/')[-1]
2200 dir = os.path.split(package.__file__)[0]
2201 path = os.path.join(dir, *(path.split('/')))
2202 doc = open(path).read()
2203
2204 if globs is None:
2205 globs = {}
2206
Edward Lopera1ef6112004-08-09 16:14:41 +00002207 test = DocTestParser().get_doctest(doc, globs, name, path, 0)
Tim Peters19397e52004-08-06 22:02:59 +00002208
2209 return DocFileCase(test, optionflags, setUp, tearDown)
2210
2211def DocFileSuite(*paths, **kw):
2212 """Creates a suite of doctest files.
2213
2214 One or more text file paths are given as strings. These should
2215 use "/" characters to separate path segments. Paths are relative
2216 to the directory of the calling module, or relative to the package
2217 passed as a keyword argument.
2218
2219 A number of options may be provided as keyword arguments:
2220
2221 package
2222 The name of a Python package. Text-file paths will be
2223 interpreted relative to the directory containing this package.
2224 The package may be supplied as a package object or as a dotted
2225 package name.
2226
2227 setUp
2228 The name of a set-up function. This is called before running the
2229 tests in each file.
2230
2231 tearDown
2232 The name of a tear-down function. This is called after running the
2233 tests in each file.
2234
2235 globs
2236 A dictionary containing initial global variables for the tests.
2237 """
2238 suite = unittest.TestSuite()
2239
2240 # We do this here so that _normalize_module is called at the right
2241 # level. If it were called in DocFileTest, then this function
2242 # would be the caller and we might guess the package incorrectly.
2243 kw['package'] = _normalize_module(kw.get('package'))
2244
2245 for path in paths:
2246 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002247
Tim Petersdb3756d2003-06-29 05:30:48 +00002248 return suite
2249
Tim Peters8485b562004-08-04 18:46:34 +00002250######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002251## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002252######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002253
Tim Peters19397e52004-08-06 22:02:59 +00002254def script_from_examples(s):
2255 r"""Extract script from text with examples.
2256
2257 Converts text with examples to a Python script. Example input is
2258 converted to regular code. Example output and all other words
2259 are converted to comments:
2260
2261 >>> text = '''
2262 ... Here are examples of simple math.
2263 ...
2264 ... Python has super accurate integer addition
2265 ...
2266 ... >>> 2 + 2
2267 ... 5
2268 ...
2269 ... And very friendly error messages:
2270 ...
2271 ... >>> 1/0
2272 ... To Infinity
2273 ... And
2274 ... Beyond
2275 ...
2276 ... You can use logic if you want:
2277 ...
2278 ... >>> if 0:
2279 ... ... blah
2280 ... ... blah
2281 ... ...
2282 ...
2283 ... Ho hum
2284 ... '''
2285
2286 >>> print script_from_examples(text)
Edward Lopera5db6002004-08-12 02:41:30 +00002287 # Here are examples of simple math.
Tim Peters19397e52004-08-06 22:02:59 +00002288 #
Edward Lopera5db6002004-08-12 02:41:30 +00002289 # Python has super accurate integer addition
Tim Peters19397e52004-08-06 22:02:59 +00002290 #
2291 2 + 2
2292 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002293 ## 5
Tim Peters19397e52004-08-06 22:02:59 +00002294 #
Edward Lopera5db6002004-08-12 02:41:30 +00002295 # And very friendly error messages:
Tim Peters19397e52004-08-06 22:02:59 +00002296 #
2297 1/0
2298 # Expected:
Edward Lopera5db6002004-08-12 02:41:30 +00002299 ## To Infinity
2300 ## And
2301 ## Beyond
Tim Peters19397e52004-08-06 22:02:59 +00002302 #
Edward Lopera5db6002004-08-12 02:41:30 +00002303 # You can use logic if you want:
Tim Peters19397e52004-08-06 22:02:59 +00002304 #
2305 if 0:
2306 blah
2307 blah
2308 <BLANKLINE>
2309 #
Edward Lopera5db6002004-08-12 02:41:30 +00002310 # Ho hum
Tim Peters19397e52004-08-06 22:02:59 +00002311 """
2312
Edward Lopera1ef6112004-08-09 16:14:41 +00002313 return DocTestParser().get_program(s)
Tim Peters19397e52004-08-06 22:02:59 +00002314
Tim Peters8485b562004-08-04 18:46:34 +00002315def _want_comment(example):
2316 """
Tim Peters19397e52004-08-06 22:02:59 +00002317 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002318 """
Jim Fultona643b652004-07-14 19:06:50 +00002319 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002320 want = example.want
2321 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002322 if want[-1] == '\n':
2323 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002324 want = "\n# ".join(want.split("\n"))
2325 want = "\n# Expected:\n# %s" % want
2326 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002327
2328def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002329 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002330
2331 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002332 test to be debugged and the name (within the module) of the object
2333 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002334 """
Tim Peters8485b562004-08-04 18:46:34 +00002335 module = _normalize_module(module)
2336 tests = DocTestFinder().find(module)
2337 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002338 if not test:
2339 raise ValueError(name, "not found in tests")
2340 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002341 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002342 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002343
Jim Fultona643b652004-07-14 19:06:50 +00002344def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002345 """Debug a single doctest docstring, in argument `src`'"""
2346 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002347 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002348
Jim Fultona643b652004-07-14 19:06:50 +00002349def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002350 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002351 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002352
Tim Petersdb3756d2003-06-29 05:30:48 +00002353 srcfilename = tempfile.mktemp("doctestdebug.py")
Tim Peters8485b562004-08-04 18:46:34 +00002354 f = open(srcfilename, 'w')
2355 f.write(src)
2356 f.close()
2357
Jim Fultona643b652004-07-14 19:06:50 +00002358 if globs:
2359 globs = globs.copy()
2360 else:
2361 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002362
Tim Peters8485b562004-08-04 18:46:34 +00002363 if pm:
2364 try:
2365 execfile(srcfilename, globs, globs)
2366 except:
2367 print sys.exc_info()[1]
2368 pdb.post_mortem(sys.exc_info()[2])
2369 else:
2370 # Note that %r is vital here. '%s' instead can, e.g., cause
2371 # backslashes to get treated as metacharacters on Windows.
2372 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002373
Jim Fultona643b652004-07-14 19:06:50 +00002374def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002375 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002376
2377 Provide the module (or dotted name of the module) containing the
2378 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002379 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002380 """
Tim Peters8485b562004-08-04 18:46:34 +00002381 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002382 testsrc = testsource(module, name)
2383 debug_script(testsrc, pm, module.__dict__)
2384
Tim Peters8485b562004-08-04 18:46:34 +00002385######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002386## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002387######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002388class _TestClass:
2389 """
2390 A pointless class, for sanity-checking of docstring testing.
2391
2392 Methods:
2393 square()
2394 get()
2395
2396 >>> _TestClass(13).get() + _TestClass(-12).get()
2397 1
2398 >>> hex(_TestClass(13).square().get())
2399 '0xa9'
2400 """
2401
2402 def __init__(self, val):
2403 """val -> _TestClass object with associated value val.
2404
2405 >>> t = _TestClass(123)
2406 >>> print t.get()
2407 123
2408 """
2409
2410 self.val = val
2411
2412 def square(self):
2413 """square() -> square TestClass's associated value
2414
2415 >>> _TestClass(13).square().get()
2416 169
2417 """
2418
2419 self.val = self.val ** 2
2420 return self
2421
2422 def get(self):
2423 """get() -> return TestClass's associated value.
2424
2425 >>> x = _TestClass(-42)
2426 >>> print x.get()
2427 -42
2428 """
2429
2430 return self.val
2431
2432__test__ = {"_TestClass": _TestClass,
2433 "string": r"""
2434 Example of a string object, searched as-is.
2435 >>> x = 1; y = 2
2436 >>> x + y, x * y
2437 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002438 """,
2439 "bool-int equivalence": r"""
2440 In 2.2, boolean expressions displayed
2441 0 or 1. By default, we still accept
2442 them. This can be disabled by passing
2443 DONT_ACCEPT_TRUE_FOR_1 to the new
2444 optionflags argument.
2445 >>> 4 == 4
2446 1
2447 >>> 4 == 4
2448 True
2449 >>> 4 > 4
2450 0
2451 >>> 4 > 4
2452 False
2453 """,
Tim Peters8485b562004-08-04 18:46:34 +00002454 "blank lines": r"""
2455 Blank lines can be marked with <BLANKLINE>:
2456 >>> print 'foo\n\nbar\n'
2457 foo
2458 <BLANKLINE>
2459 bar
2460 <BLANKLINE>
2461 """,
2462 }
2463# "ellipsis": r"""
2464# If the ellipsis flag is used, then '...' can be used to
2465# elide substrings in the desired output:
2466# >>> print range(1000)
2467# [0, 1, 2, ..., 999]
2468# """,
2469# "whitespace normalization": r"""
2470# If the whitespace normalization flag is used, then
2471# differences in whitespace are ignored.
2472# >>> print range(30)
2473# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2474# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2475# 27, 28, 29]
2476# """,
2477# }
2478
2479def test1(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002480>>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2481... "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002482>>> from doctest import Tester
2483>>> t = Tester(globs={'x': 42}, verbose=0)
2484>>> t.runstring(r'''
2485... >>> x = x * 2
2486... >>> print x
2487... 42
2488... ''', 'XYZ')
2489**********************************************************************
Jim Fulton07a349c2004-08-22 14:10:00 +00002490Line 3, in XYZ
2491Failed example:
2492 print x
2493Expected:
2494 42
2495Got:
2496 84
Tim Peters8485b562004-08-04 18:46:34 +00002497(1, 2)
2498>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2499(0, 2)
2500>>> t.summarize()
2501**********************************************************************
25021 items had failures:
2503 1 of 2 in XYZ
2504***Test Failed*** 1 failures.
2505(1, 4)
2506>>> t.summarize(verbose=1)
25071 items passed all tests:
2508 2 tests in example2
2509**********************************************************************
25101 items had failures:
2511 1 of 2 in XYZ
25124 tests in 2 items.
25133 passed and 1 failed.
2514***Test Failed*** 1 failures.
2515(1, 4)
2516"""
2517
2518def test2(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002519 >>> warnings.filterwarnings("ignore", "class Tester",
2520 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002521 >>> t = Tester(globs={}, verbose=1)
2522 >>> test = r'''
2523 ... # just an example
2524 ... >>> x = 1 + 2
2525 ... >>> x
2526 ... 3
2527 ... '''
2528 >>> t.runstring(test, "Example")
2529 Running string Example
2530 Trying: x = 1 + 2
2531 Expecting: nothing
2532 ok
2533 Trying: x
2534 Expecting: 3
2535 ok
2536 0 of 2 examples failed in string Example
2537 (0, 2)
2538"""
2539def test3(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002540 >>> warnings.filterwarnings("ignore", "class Tester",
2541 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002542 >>> t = Tester(globs={}, verbose=0)
2543 >>> def _f():
2544 ... '''Trivial docstring example.
2545 ... >>> assert 2 == 2
2546 ... '''
2547 ... return 32
2548 ...
2549 >>> t.rundoc(_f) # expect 0 failures in 1 example
2550 (0, 1)
2551"""
2552def test4(): """
2553 >>> import new
2554 >>> m1 = new.module('_m1')
2555 >>> m2 = new.module('_m2')
2556 >>> test_data = \"""
2557 ... def _f():
2558 ... '''>>> assert 1 == 1
2559 ... '''
2560 ... def g():
2561 ... '''>>> assert 2 != 1
2562 ... '''
2563 ... class H:
2564 ... '''>>> assert 2 > 1
2565 ... '''
2566 ... def bar(self):
2567 ... '''>>> assert 1 < 2
2568 ... '''
2569 ... \"""
2570 >>> exec test_data in m1.__dict__
2571 >>> exec test_data in m2.__dict__
2572 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2573
2574 Tests that objects outside m1 are excluded:
2575
Tim Peters3ddd60a2004-08-08 02:43:33 +00002576 >>> warnings.filterwarnings("ignore", "class Tester",
2577 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002578 >>> t = Tester(globs={}, verbose=0)
Tim Petersf727c6c2004-08-08 01:48:59 +00002579 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Tim Peters8485b562004-08-04 18:46:34 +00002580 (0, 4)
2581
Tim Petersf727c6c2004-08-08 01:48:59 +00002582 Once more, not excluding stuff outside m1:
Tim Peters8485b562004-08-04 18:46:34 +00002583
2584 >>> t = Tester(globs={}, verbose=0)
2585 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2586 (0, 8)
2587
2588 The exclusion of objects from outside the designated module is
2589 meant to be invoked automagically by testmod.
2590
Tim Petersf727c6c2004-08-08 01:48:59 +00002591 >>> testmod(m1, verbose=False)
2592 (0, 4)
Tim Peters8485b562004-08-04 18:46:34 +00002593"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002594
2595def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002596 #import doctest
2597 #doctest.testmod(doctest, verbose=False,
2598 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2599 # UNIFIED_DIFF)
2600 #print '~'*70
2601 r = unittest.TextTestRunner()
2602 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002603
2604if __name__ == "__main__":
2605 _test()