blob: 4c651ed879957b0f7bc45ce570c787368872ca8a [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
Tim Peters8485b562004-08-04 18:46:34 +00009# [XX] This docstring is out-of-date:
Martin v. Löwis92816de2004-05-31 19:01:00 +000010r"""Module doctest -- a framework for running examples in docstrings.
Tim Peters8a7d2d52001-01-16 07:10:57 +000011
12NORMAL USAGE
13
14In normal use, end each module M with:
15
16def _test():
17 import doctest, M # replace M with your module's name
18 return doctest.testmod(M) # ditto
19
20if __name__ == "__main__":
21 _test()
22
23Then running the module as a script will cause the examples in the
24docstrings to get executed and verified:
25
26python M.py
27
28This won't display anything unless an example fails, in which case the
29failing example(s) and the cause(s) of the failure(s) are printed to stdout
30(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
31line of output is "Test failed.".
32
33Run it with the -v switch instead:
34
35python M.py -v
36
37and a detailed report of all examples tried is printed to stdout, along
38with assorted summaries at the end.
39
40You can force verbose mode by passing "verbose=1" to testmod, or prohibit
41it by passing "verbose=0". In either of those cases, sys.argv is not
42examined by testmod.
43
44In any case, testmod returns a 2-tuple of ints (f, t), where f is the
45number of docstring examples that failed and t is the total number of
46docstring examples attempted.
47
48
49WHICH DOCSTRINGS ARE EXAMINED?
50
51+ M.__doc__.
52
53+ f.__doc__ for all functions f in M.__dict__.values(), except those
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000054 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000055
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000056+ C.__doc__ for all classes C in M.__dict__.values(), except those
57 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000058
59+ If M.__test__ exists and "is true", it must be a dict, and
60 each entry maps a (string) name to a function object, class object, or
61 string. Function and class object docstrings found from M.__test__
62 are searched even if the name is private, and strings are searched
63 directly as if they were docstrings. In output, a key K in M.__test__
64 appears with name
65 <name of M>.__test__.K
66
67Any classes found are recursively searched similarly, to test docstrings in
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000068their contained methods and nested classes. All names reached from
69M.__test__ are searched.
Tim Peters8a7d2d52001-01-16 07:10:57 +000070
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000071Optionally, functions with private names can be skipped (unless listed in
72M.__test__) by supplying a function to the "isprivate" argument that will
73identify private functions. For convenience, one such function is
74supplied. docttest.is_private considers a name to be private if it begins
75with an underscore (like "_my_func") but doesn't both begin and end with
76(at least) two underscores (like "__init__"). By supplying this function
77or your own "isprivate" function to testmod, the behavior can be customized.
Tim Peters8a7d2d52001-01-16 07:10:57 +000078
79If you want to test docstrings in objects with private names too, stuff
80them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
81own isprivate function to Tester's constructor, or call the rundoc method
82of a Tester instance).
83
Tim Peters8a7d2d52001-01-16 07:10:57 +000084WHAT'S THE EXECUTION CONTEXT?
85
86By default, each time testmod finds a docstring to test, it uses a *copy*
87of M's globals (so that running tests on a module doesn't change the
88module's real globals, and so that one test in M can't leave behind crumbs
89that accidentally allow another test to work). This means examples can
90freely use any names defined at top-level in M. It also means that sloppy
91imports (see above) can cause examples in external docstrings to use
92globals inappropriate for them.
93
94You can force use of your own dict as the execution context by passing
95"globs=your_dict" to testmod instead. Presumably this would be a copy of
96M.__dict__ merged with the globals from other imported modules.
97
98
99WHAT IF I WANT TO TEST A WHOLE PACKAGE?
100
101Piece o' cake, provided the modules do their testing from docstrings.
102Here's the test.py I use for the world's most elaborate Rational/
103floating-base-conversion pkg (which I'll distribute some day):
104
105from Rational import Cvt
106from Rational import Format
107from Rational import machprec
108from Rational import Rat
109from Rational import Round
110from Rational import utils
111
112modules = (Cvt,
113 Format,
114 machprec,
115 Rat,
116 Round,
117 utils)
118
119def _test():
120 import doctest
121 import sys
122 verbose = "-v" in sys.argv
123 for mod in modules:
124 doctest.testmod(mod, verbose=verbose, report=0)
125 doctest.master.summarize()
126
127if __name__ == "__main__":
128 _test()
129
130IOW, it just runs testmod on all the pkg modules. testmod remembers the
131names and outcomes (# of failures, # of tries) for each item it's seen, and
132passing "report=0" prevents it from printing a summary in verbose mode.
133Instead, the summary is delayed until all modules have been tested, and
134then "doctest.master.summarize()" forces the summary at the end.
135
136So this is very nice in practice: each module can be tested individually
137with almost no work beyond writing up docstring examples, and collections
138of modules can be tested too as a unit with no more work than the above.
139
140
141WHAT ABOUT EXCEPTIONS?
142
143No problem, as long as the only output generated by the example is the
144traceback itself. For example:
145
Tim Peters60e23f42001-02-14 00:43:21 +0000146 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +0000147 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000148 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000149 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000150 >>>
151
152Note that only the exception type and value are compared (specifically,
153only the last line in the traceback).
154
155
156ADVANCED USAGE
157
158doctest.testmod() captures the testing policy I find most useful most
159often. You may want other policies.
160
161testmod() actually creates a local instance of class doctest.Tester, runs
162appropriate methods of that class, and merges the results into global
163Tester instance doctest.master.
164
165You can create your own instances of doctest.Tester, and so build your own
166policies, or even run methods of doctest.master directly. See
167doctest.Tester.__doc__ for details.
168
169
170SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
171
172Oh ya. It's easy! In most cases a copy-and-paste of an interactive
173console session works fine -- just make sure the leading whitespace is
174rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
175right, but doctest is not in the business of guessing what you think a tab
176means).
177
178 >>> # comments are ignored
179 >>> x = 12
180 >>> x
181 12
182 >>> if x == 13:
183 ... print "yes"
184 ... else:
185 ... print "no"
186 ... print "NO"
187 ... print "NO!!!"
188 ...
189 no
190 NO
191 NO!!!
192 >>>
193
194Any expected output must immediately follow the final ">>>" or "..." line
195containing the code, and the expected output (if any) extends to the next
196">>>" or all-whitespace line. That's it.
197
198Bummers:
199
200+ Expected output cannot contain an all-whitespace line, since such a line
201 is taken to signal the end of expected output.
202
203+ Output to stdout is captured, but not output to stderr (exception
204 tracebacks are captured via a different means).
205
Martin v. Löwis92816de2004-05-31 19:01:00 +0000206+ If you continue a line via backslashing in an interactive session,
207 or for any other reason use a backslash, you should use a raw
208 docstring, which will preserve your backslahses exactly as you type
209 them:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000210
Tim Peters4e0e1b62004-07-07 20:54:48 +0000211 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000212 ... r'''Backslashes in a raw docstring: m\n'''
213 >>> print f.__doc__
214 Backslashes in a raw docstring: m\n
Tim Peters8a7d2d52001-01-16 07:10:57 +0000215
Martin v. Löwis92816de2004-05-31 19:01:00 +0000216 Otherwise, the backslash will be interpreted as part of the string.
217 E.g., the "\n" above would be interpreted as a newline character.
218 Alternatively, you can double each backslash in the doctest version
219 (and not use a raw string):
220
Tim Peters4e0e1b62004-07-07 20:54:48 +0000221 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000222 ... '''Backslashes in a raw docstring: m\\n'''
223 >>> print f.__doc__
224 Backslashes in a raw docstring: m\n
Tim Peters4e0e1b62004-07-07 20:54:48 +0000225
Tim Peters8a7d2d52001-01-16 07:10:57 +0000226The starting column doesn't matter:
227
228>>> assert "Easy!"
229 >>> import math
230 >>> math.floor(1.9)
231 1.0
232
233and as many leading whitespace characters are stripped from the expected
234output as appeared in the initial ">>>" line that triggered it.
235
236If you execute this very file, the examples above will be found and
237executed, leading to this output in verbose mode:
238
239Running doctest.__doc__
Tim Peters60e23f42001-02-14 00:43:21 +0000240Trying: [1, 2, 3].remove(42)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000241Expecting:
Tim Petersea4f9312001-02-13 20:54:42 +0000242Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000243 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000244ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000245ok
246Trying: x = 12
247Expecting: nothing
248ok
249Trying: x
250Expecting: 12
251ok
252Trying:
253if x == 13:
254 print "yes"
255else:
256 print "no"
257 print "NO"
258 print "NO!!!"
259Expecting:
260no
261NO
262NO!!!
263ok
264... and a bunch more like that, with this summary at the end:
265
2665 items had no tests:
267 doctest.Tester.__init__
268 doctest.Tester.run__test__
269 doctest.Tester.summarize
270 doctest.run_docstring_examples
271 doctest.testmod
27212 items passed all tests:
273 8 tests in doctest
274 6 tests in doctest.Tester
275 10 tests in doctest.Tester.merge
Tim Peters17111f32001-10-03 04:08:26 +0000276 14 tests in doctest.Tester.rundict
Tim Peters8a7d2d52001-01-16 07:10:57 +0000277 3 tests in doctest.Tester.rundoc
278 3 tests in doctest.Tester.runstring
279 2 tests in doctest.__test__._TestClass
280 2 tests in doctest.__test__._TestClass.__init__
281 2 tests in doctest.__test__._TestClass.get
282 1 tests in doctest.__test__._TestClass.square
283 2 tests in doctest.__test__.string
284 7 tests in doctest.is_private
Tim Peters17111f32001-10-03 04:08:26 +000028560 tests in 17 items.
28660 passed and 0 failed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000287Test passed.
288"""
289
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000290__all__ = [
Tim Peters8485b562004-08-04 18:46:34 +0000291 'is_private',
292 'Example',
293 'DocTest',
294 'DocTestFinder',
295 'DocTestRunner',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000296 'testmod',
297 'run_docstring_examples',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000298 'Tester',
Tim Peters19397e52004-08-06 22:02:59 +0000299 'DocTestCase',
Tim Petersdb3756d2003-06-29 05:30:48 +0000300 'DocTestSuite',
301 'testsource',
302 'debug',
Tim Peters8485b562004-08-04 18:46:34 +0000303# 'master',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000304]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000305
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000306import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000307
Tim Peters19397e52004-08-06 22:02:59 +0000308import sys, traceback, inspect, linecache, os, re, types
Tim Peters8485b562004-08-04 18:46:34 +0000309import unittest, difflib, tempfile
Tim Petersf727c6c2004-08-08 01:48:59 +0000310import warnings
Tim Peters8485b562004-08-04 18:46:34 +0000311from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000312
Tim Peters6ebe61f2003-06-27 20:48:05 +0000313# Option constants.
314DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
Tim Peters8485b562004-08-04 18:46:34 +0000315DONT_ACCEPT_BLANKLINE = 1 << 1
316NORMALIZE_WHITESPACE = 1 << 2
317ELLIPSIS = 1 << 3
318UNIFIED_DIFF = 1 << 4
319CONTEXT_DIFF = 1 << 5
Tim Peters6ebe61f2003-06-27 20:48:05 +0000320
Tim Peters8485b562004-08-04 18:46:34 +0000321OPTIONFLAGS_BY_NAME = {
322 'DONT_ACCEPT_TRUE_FOR_1': DONT_ACCEPT_TRUE_FOR_1,
323 'DONT_ACCEPT_BLANKLINE': DONT_ACCEPT_BLANKLINE,
324 'NORMALIZE_WHITESPACE': NORMALIZE_WHITESPACE,
325 'ELLIPSIS': ELLIPSIS,
326 'UNIFIED_DIFF': UNIFIED_DIFF,
327 'CONTEXT_DIFF': CONTEXT_DIFF,
328 }
Tim Peters8a7d2d52001-01-16 07:10:57 +0000329
Tim Peters8485b562004-08-04 18:46:34 +0000330# Special string markers for use in `want` strings:
331BLANKLINE_MARKER = '<BLANKLINE>'
332ELLIPSIS_MARKER = '...'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000333
Tim Peters19397e52004-08-06 22:02:59 +0000334
335# There are 4 basic classes:
336# - Example: a <source, want> pair, plus an intra-docstring line number.
337# - DocTest: a collection of examples, parsed from a docstring, plus
338# info about where the docstring came from (name, filename, lineno).
339# - DocTestFinder: extracts DocTests from a given object's docstring and
340# its contained objects' docstrings.
341# - DocTestRunner: runs DocTest cases, and accumulates statistics.
342#
343# So the basic picture is:
344#
345# list of:
346# +------+ +---------+ +-------+
347# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
348# +------+ +---------+ +-------+
349# | Example |
350# | ... |
351# | Example |
352# +---------+
353
Tim Peters8485b562004-08-04 18:46:34 +0000354######################################################################
355## Table of Contents
356######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000357# 1. Utility Functions
358# 2. Example & DocTest -- store test cases
359# 3. DocTest Parser -- extracts examples from strings
360# 4. DocTest Finder -- extracts test cases from objects
361# 5. DocTest Runner -- runs test cases
362# 6. Test Functions -- convenient wrappers for testing
363# 7. Tester Class -- for backwards compatibility
364# 8. Unittest Support
365# 9. Debugging Support
366# 10. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000367
Tim Peters8485b562004-08-04 18:46:34 +0000368######################################################################
369## 1. Utility Functions
370######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000371
372def is_private(prefix, base):
373 """prefix, base -> true iff name prefix + "." + base is "private".
374
375 Prefix may be an empty string, and base does not contain a period.
376 Prefix is ignored (although functions you write conforming to this
377 protocol may make use of it).
378 Return true iff base begins with an (at least one) underscore, but
379 does not both begin and end with (at least) two underscores.
380
Tim Petersbafb1fe2004-08-08 01:52:57 +0000381 >>> warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
382 ... "doctest", 0)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000383 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000384 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000385 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000386 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000387 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000388 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000389 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000390 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000391 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000392 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000393 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000394 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000395 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000396 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000397 """
Tim Petersbafb1fe2004-08-08 01:52:57 +0000398 warnings.warn("is_private is deprecated; it wasn't useful; "
399 "examine DocTestFinder.find() lists instead",
Tim Peters3ddd60a2004-08-08 02:43:33 +0000400 DeprecationWarning, stacklevel=2)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000401 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
402
Tim Peters8485b562004-08-04 18:46:34 +0000403def _extract_future_flags(globs):
404 """
405 Return the compiler-flags associated with the future features that
406 have been imported into the given namespace (globs).
407 """
408 flags = 0
409 for fname in __future__.all_feature_names:
410 feature = globs.get(fname, None)
411 if feature is getattr(__future__, fname):
412 flags |= feature.compiler_flag
413 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000414
Tim Peters8485b562004-08-04 18:46:34 +0000415def _normalize_module(module, depth=2):
416 """
417 Return the module specified by `module`. In particular:
418 - If `module` is a module, then return module.
419 - If `module` is a string, then import and return the
420 module with that name.
421 - If `module` is None, then return the calling module.
422 The calling module is assumed to be the module of
423 the stack frame at the given depth in the call stack.
424 """
425 if inspect.ismodule(module):
426 return module
427 elif isinstance(module, (str, unicode)):
428 return __import__(module, globals(), locals(), ["*"])
429 elif module is None:
430 return sys.modules[sys._getframe(depth).f_globals['__name__']]
431 else:
432 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000433
Tim Peters8485b562004-08-04 18:46:34 +0000434def _tag_msg(tag, msg, indent_msg=True):
435 """
436 Return a string that displays a tag-and-message pair nicely,
437 keeping the tag and its message on the same line when that
438 makes sense. If `indent_msg` is true, then messages that are
439 put on separate lines will be indented.
440 """
441 # What string should we use to indent contents?
442 INDENT = ' '
Tim Peters8a7d2d52001-01-16 07:10:57 +0000443
Tim Peters8485b562004-08-04 18:46:34 +0000444 # If the message doesn't end in a newline, then add one.
445 if msg[-1:] != '\n':
446 msg += '\n'
447 # If the message is short enough, and contains no internal
448 # newlines, then display it on the same line as the tag.
449 # Otherwise, display the tag on its own line.
450 if (len(tag) + len(msg) < 75 and
451 msg.find('\n', 0, len(msg)-1) == -1):
452 return '%s: %s' % (tag, msg)
453 else:
454 if indent_msg:
455 msg = '\n'.join([INDENT+l for l in msg.split('\n')])
456 msg = msg[:-len(INDENT)]
457 return '%s:\n%s' % (tag, msg)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000458
Tim Peters8485b562004-08-04 18:46:34 +0000459# Override some StringIO methods.
460class _SpoofOut(StringIO):
461 def getvalue(self):
462 result = StringIO.getvalue(self)
463 # If anything at all was written, make sure there's a trailing
464 # newline. There's no way for the expected output to indicate
465 # that a trailing newline is missing.
466 if result and not result.endswith("\n"):
467 result += "\n"
468 # Prevent softspace from screwing up the next test case, in
469 # case they used print with a trailing comma in an example.
470 if hasattr(self, "softspace"):
471 del self.softspace
472 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000473
Tim Peters8485b562004-08-04 18:46:34 +0000474 def truncate(self, size=None):
475 StringIO.truncate(self, size)
476 if hasattr(self, "softspace"):
477 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000478
Tim Peters8485b562004-08-04 18:46:34 +0000479######################################################################
480## 2. Example & DocTest
481######################################################################
482## - An "example" is a <source, want> pair, where "source" is a
483## fragment of source code, and "want" is the expected output for
484## "source." The Example class also includes information about
485## where the example was extracted from.
486##
487## - A "doctest" is a collection of examples extracted from a string
488## (such as an object's docstring). The DocTest class also includes
489## information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000490
Tim Peters8485b562004-08-04 18:46:34 +0000491class Example:
492 """
493 A single doctest example, consisting of source code and expected
494 output. Example defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000495
Tim Peters8485b562004-08-04 18:46:34 +0000496 - source: The source code that should be run. It ends with a
497 newline iff the source spans more than one line.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000498
Tim Peters8485b562004-08-04 18:46:34 +0000499 - want: The expected output from running the source code. If
500 not empty, then this string ends with a newline.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000501
Tim Peters8485b562004-08-04 18:46:34 +0000502 - lineno: The line number within the DocTest string containing
503 this Example where the Example begins. This line number is
504 zero-based, with respect to the beginning of the DocTest.
505 """
506 def __init__(self, source, want, lineno):
507 # Check invariants.
Tim Peters9b625d32004-08-04 20:04:32 +0000508 if (source[-1:] == '\n') != ('\n' in source[:-1]):
509 raise AssertionError("source must end with newline iff "
510 "source contains more than one line")
511 if want and want[-1] != '\n':
512 raise AssertionError("non-empty want must end with newline")
Tim Peters8485b562004-08-04 18:46:34 +0000513 # Store properties.
514 self.source = source
515 self.want = want
516 self.lineno = lineno
Tim Peters8a7d2d52001-01-16 07:10:57 +0000517
Tim Peters8485b562004-08-04 18:46:34 +0000518class DocTest:
519 """
520 A collection of doctest examples that should be run in a single
521 namespace. Each DocTest defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000522
Tim Peters8485b562004-08-04 18:46:34 +0000523 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000524
Tim Peters8485b562004-08-04 18:46:34 +0000525 - globs: The namespace (aka globals) that the examples should
526 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000527
Tim Peters8485b562004-08-04 18:46:34 +0000528 - name: A name identifying the DocTest (typically, the name of
529 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000530
Tim Peters19397e52004-08-06 22:02:59 +0000531 - docstring: The docstring being tested
532
Tim Peters8485b562004-08-04 18:46:34 +0000533 - filename: The name of the file that this DocTest was extracted
534 from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000535
Tim Peters8485b562004-08-04 18:46:34 +0000536 - lineno: The line number within filename where this DocTest
537 begins. This line number is zero-based, with respect to the
538 beginning of the file.
539 """
540 def __init__(self, docstring, globs, name, filename, lineno):
541 """
542 Create a new DocTest, by extracting examples from `docstring`.
543 The DocTest's globals are initialized with a copy of `globs`.
544 """
545 # Store a copy of the globals
546 self.globs = globs.copy()
547 # Store identifying information
548 self.name = name
549 self.filename = filename
550 self.lineno = lineno
551 # Parse the docstring.
Tim Peters19397e52004-08-06 22:02:59 +0000552 self.docstring = docstring
553 examples = Parser(name, docstring).get_examples()
554 self.examples = [Example(*example) for example in examples]
Tim Peters8485b562004-08-04 18:46:34 +0000555
556 def __repr__(self):
557 if len(self.examples) == 0:
558 examples = 'no examples'
559 elif len(self.examples) == 1:
560 examples = '1 example'
561 else:
562 examples = '%d examples' % len(self.examples)
563 return ('<DocTest %s from %s:%s (%s)>' %
564 (self.name, self.filename, self.lineno, examples))
565
566
567 # This lets us sort tests by name:
568 def __cmp__(self, other):
569 if not isinstance(other, DocTest):
570 return -1
571 return cmp((self.name, self.filename, self.lineno, id(self)),
572 (other.name, other.filename, other.lineno, id(other)))
573
574######################################################################
Edward Loper7c748462004-08-09 02:06:06 +0000575## 2. Example Parser
576######################################################################
577
578class Parser:
579 """
580 Extract doctests from a string.
581 """
582 def __init__(self, name, string):
583 """
584 Prepare to extract doctests from string `string`.
585
586 `name` is an arbitrary (string) name associated with the string,
587 and is used only in error messages.
588 """
589 self.name = name
590 self.string = string.expandtabs()
591
592 _EXAMPLE_RE = re.compile(r'''
593 # Source consists of a PS1 line followed by zero or more PS2 lines.
594 (?P<source>
595 (?:^(?P<indent> [ ]*) >>> .*) # PS1 line
596 (?:\n [ ]* \.\.\. .*)*) # PS2 lines
597 \n?
598 # Want consists of any non-blank lines that do not start with PS1.
599 (?P<want> (?:(?![ ]*$) # Not a blank line
600 (?![ ]*>>>) # Not a line starting with PS1
601 .*$\n? # But any other line
602 )*)
603 ''', re.MULTILINE | re.VERBOSE)
604 _IS_BLANK_OR_COMMENT = re.compile('^[ ]*(#.*)?$')
605
606 def get_examples(self):
607 """
608 Return the doctest examples from the string.
609
610 This is a list of (source, want, lineno) triples, one per example
611 in the string. "source" is a single Python statement; it ends
612 with a newline iff the statement contains more than one
613 physical line. "want" is the expected output from running the
614 example (either from stdout, or a traceback in case of exception).
615 "want" always ends with a newline, unless no output is expected,
616 in which case "want" is an empty string. "lineno" is the 0-based
617 line number of the first line of "source" within the string. It's
618 0-based because it's most common in doctests that nothing
619 interesting appears on the same line as opening triple-quote,
620 and so the first interesting line is called "line 1" then.
621
622 >>> text = '''
623 ... >>> x, y = 2, 3 # no output expected
624 ... >>> if 1:
625 ... ... print x
626 ... ... print y
627 ... 2
628 ... 3
629 ...
630 ... Some text.
631 ... >>> x+y
632 ... 5
633 ... '''
634 >>> for x in Parser('<string>', text).get_examples():
635 ... print x
636 ('x, y = 2, 3 # no output expected', '', 1)
637 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
638 ('x+y', '5\\n', 9)
639 """
640 examples = []
641 charno, lineno = 0, 0
642 # Find all doctest examples in the string:
643 for m in self._EXAMPLE_RE.finditer(self.string):
644 # Update lineno (lines before this example)
645 lineno += self.string.count('\n', charno, m.start())
646
647 # Extract source/want from the regexp match.
648 (source, want) = self._parse_example(m, lineno)
649 if self._IS_BLANK_OR_COMMENT.match(source):
650 continue
651 examples.append( (source, want, lineno) )
652
653 # Update lineno (lines inside this example)
654 lineno += self.string.count('\n', m.start(), m.end())
655 # Update charno.
656 charno = m.end()
657 return examples
658
659 def get_program(self):
660 """
661 Return an executable program from the string, as a string.
662
663 The format of this isn't rigidly defined. In general, doctest
664 examples become the executable statements in the result, and
665 their expected outputs become comments, preceded by an \"#Expected:\"
666 comment. Everything else (text, comments, everything not part of
667 a doctest test) is also placed in comments.
668
669 >>> text = '''
670 ... >>> x, y = 2, 3 # no output expected
671 ... >>> if 1:
672 ... ... print x
673 ... ... print y
674 ... 2
675 ... 3
676 ...
677 ... Some text.
678 ... >>> x+y
679 ... 5
680 ... '''
681 >>> print Parser('<string>', text).get_program()
682 x, y = 2, 3 # no output expected
683 if 1:
684 print x
685 print y
686 # Expected:
687 # 2
688 # 3
689 #
690 # Some text.
691 x+y
692 # Expected:
693 # 5
694 """
695 output = []
696 charnum, lineno = 0, 0
697 # Find all doctest examples in the string:
698 for m in self._EXAMPLE_RE.finditer(self.string):
699 # Add any text before this example, as a comment.
700 if m.start() > charnum:
701 lines = self.string[charnum:m.start()-1].split('\n')
702 output.extend([self._comment_line(l) for l in lines])
703 lineno += len(lines)
704
705 # Extract source/want from the regexp match.
706 (source, want) = self._parse_example(m, lineno, False)
707 # Display the source
708 output.append(source)
709 # Display the expected output, if any
710 if want:
711 output.append('# Expected:')
712 output.extend(['# '+l for l in want.split('\n')])
713
714 # Update the line number & char number.
715 lineno += self.string.count('\n', m.start(), m.end())
716 charnum = m.end()
717 # Add any remaining text, as comments.
718 output.extend([self._comment_line(l)
719 for l in self.string[charnum:].split('\n')])
720 # Trim junk on both ends.
721 while output and output[-1] == '#':
722 output.pop()
723 while output and output[0] == '#':
724 output.pop(0)
725 # Combine the output, and return it.
726 return '\n'.join(output)
727
728 def _parse_example(self, m, lineno, add_newlines=True):
729 # Get the example's indentation level.
730 indent = len(m.group('indent'))
731
732 # Divide source into lines; check that they're properly
733 # indented; and then strip their indentation & prompts.
734 source_lines = m.group('source').split('\n')
735 self._check_prompt_blank(source_lines, indent, lineno)
736 self._check_prefix(source_lines[1:], ' '*indent+'.', lineno)
737 source = '\n'.join([sl[indent+4:] for sl in source_lines])
738 if len(source_lines) > 1 and add_newlines:
739 source += '\n'
740
741 # Divide want into lines; check that it's properly
742 # indented; and then strip the indentation.
743 want_lines = m.group('want').rstrip().split('\n')
744 self._check_prefix(want_lines, ' '*indent,
745 lineno+len(source_lines))
746 want = '\n'.join([wl[indent:] for wl in want_lines])
747 if len(want) > 0 and add_newlines:
748 want += '\n'
749
750 return source, want
751
752 def _comment_line(self, line):
753 line = line.rstrip()
754 if line: return '# '+line
755 else: return '#'
756
757 def _check_prompt_blank(self, lines, indent, lineno):
758 for i, line in enumerate(lines):
759 if len(line) >= indent+4 and line[indent+3] != ' ':
760 raise ValueError('line %r of the docstring for %s '
761 'lacks blank after %s: %r' %
762 (lineno+i+1, self.name,
763 line[indent:indent+3], line))
764
765 def _check_prefix(self, lines, prefix, lineno):
766 for i, line in enumerate(lines):
767 if line and not line.startswith(prefix):
768 raise ValueError('line %r of the docstring for %s has '
769 'inconsistent leading whitespace: %r' %
770 (lineno+i+1, self.name, line))
771
772
773######################################################################
774## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000775######################################################################
776
777class DocTestFinder:
778 """
779 A class used to extract the DocTests that are relevant to a given
780 object, from its docstring and the docstrings of its contained
781 objects. Doctests can currently be extracted from the following
782 object types: modules, functions, classes, methods, staticmethods,
783 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000784 """
785
Tim Peters19397e52004-08-06 22:02:59 +0000786 def __init__(self, verbose=False, doctest_factory=DocTest,
Tim Petersf727c6c2004-08-08 01:48:59 +0000787 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000788 """
789 Create a new doctest finder.
790
Tim Peters19397e52004-08-06 22:02:59 +0000791 The optional argument `doctest_factory` specifies a class or
792 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000793 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000794 signature for this factory function should match the signature
795 of the DocTest constructor.
796
Tim Peters8485b562004-08-04 18:46:34 +0000797 If the optional argument `recurse` is false, then `find` will
798 only examine the given object, and not any contained objects.
799 """
Tim Peters19397e52004-08-06 22:02:59 +0000800 self._doctest_factory = doctest_factory
Tim Peters8485b562004-08-04 18:46:34 +0000801 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000802 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000803 # _namefilter is undocumented, and exists only for temporary backward-
804 # compatibility support of testmod's deprecated isprivate mess.
805 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000806
807 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000808 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000809 """
810 Return a list of the DocTests that are defined by the given
811 object's docstring, or by any of its contained objects'
812 docstrings.
813
814 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000815 the given object. If the module is not specified or is None, then
816 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000817 correct module. The object's module is used:
818
819 - As a default namespace, if `globs` is not specified.
820 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000821 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000822 - To find the name of the file containing the object.
823 - To help find the line number of the object within its
824 file.
825
Tim Petersf3f57472004-08-08 06:11:48 +0000826 Contained objects whose module does not match `module` are ignored.
827
828 If `module` is False, no attempt to find the module will be made.
829 This is obscure, of use mostly in tests: if `module` is False, or
830 is None but cannot be found automatically, then all objects are
831 considered to belong to the (non-existent) module, so all contained
832 objects will (recursively) be searched for doctests.
833
Tim Peters8485b562004-08-04 18:46:34 +0000834 The globals for each DocTest is formed by combining `globs`
835 and `extraglobs` (bindings in `extraglobs` override bindings
836 in `globs`). A new copy of the globals dictionary is created
837 for each DocTest. If `globs` is not specified, then it
838 defaults to the module's `__dict__`, if specified, or {}
839 otherwise. If `extraglobs` is not specified, then it defaults
840 to {}.
841
Tim Peters8485b562004-08-04 18:46:34 +0000842 """
843 # If name was not specified, then extract it from the object.
844 if name is None:
845 name = getattr(obj, '__name__', None)
846 if name is None:
847 raise ValueError("DocTestFinder.find: name must be given "
848 "when obj.__name__ doesn't exist: %r" %
849 (type(obj),))
850
851 # Find the module that contains the given object (if obj is
852 # a module, then module=obj.). Note: this may fail, in which
853 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000854 if module is False:
855 module = None
856 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000857 module = inspect.getmodule(obj)
858
859 # Read the module's source code. This is used by
860 # DocTestFinder._find_lineno to find the line number for a
861 # given object's docstring.
862 try:
863 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
864 source_lines = linecache.getlines(file)
865 if not source_lines:
866 source_lines = None
867 except TypeError:
868 source_lines = None
869
870 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000871 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000872 if module is None:
873 globs = {}
874 else:
875 globs = module.__dict__.copy()
876 else:
877 globs = globs.copy()
878 if extraglobs is not None:
879 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000880
Tim Peters8485b562004-08-04 18:46:34 +0000881 # Recursively expore `obj`, extracting DocTests.
882 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000883 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000884 return tests
885
886 def _filter(self, obj, prefix, base):
887 """
888 Return true if the given object should not be examined.
889 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000890 return (self._namefilter is not None and
891 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000892
893 def _from_module(self, module, object):
894 """
895 Return true if the given object is defined in the given
896 module.
897 """
898 if module is None:
899 return True
900 elif inspect.isfunction(object):
901 return module.__dict__ is object.func_globals
902 elif inspect.isclass(object):
903 return module.__name__ == object.__module__
904 elif inspect.getmodule(object) is not None:
905 return module is inspect.getmodule(object)
906 elif hasattr(object, '__module__'):
907 return module.__name__ == object.__module__
908 elif isinstance(object, property):
909 return True # [XX] no way not be sure.
910 else:
911 raise ValueError("object must be a class or function")
912
Tim Petersf3f57472004-08-08 06:11:48 +0000913 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000914 """
915 Find tests for the given object and any contained objects, and
916 add them to `tests`.
917 """
918 if self._verbose:
919 print 'Finding tests in %s' % name
920
921 # If we've already processed this object, then ignore it.
922 if id(obj) in seen:
923 return
924 seen[id(obj)] = 1
925
926 # Find a test for this object, and add it to the list of tests.
927 test = self._get_test(obj, name, module, globs, source_lines)
928 if test is not None:
929 tests.append(test)
930
931 # Look for tests in a module's contained objects.
932 if inspect.ismodule(obj) and self._recurse:
933 for valname, val in obj.__dict__.items():
934 # Check if this contained object should be ignored.
935 if self._filter(val, name, valname):
936 continue
937 valname = '%s.%s' % (name, valname)
938 # Recurse to functions & classes.
939 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000940 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000941 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000942 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000943
944 # Look for tests in a module's __test__ dictionary.
945 if inspect.ismodule(obj) and self._recurse:
946 for valname, val in getattr(obj, '__test__', {}).items():
947 if not isinstance(valname, basestring):
948 raise ValueError("DocTestFinder.find: __test__ keys "
949 "must be strings: %r" %
950 (type(valname),))
951 if not (inspect.isfunction(val) or inspect.isclass(val) or
952 inspect.ismethod(val) or inspect.ismodule(val) or
953 isinstance(val, basestring)):
954 raise ValueError("DocTestFinder.find: __test__ values "
955 "must be strings, functions, methods, "
956 "classes, or modules: %r" %
957 (type(val),))
958 valname = '%s.%s' % (name, valname)
959 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000960 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000961
962 # Look for tests in a class's contained objects.
963 if inspect.isclass(obj) and self._recurse:
964 for valname, val in obj.__dict__.items():
965 # Check if this contained object should be ignored.
966 if self._filter(val, name, valname):
967 continue
968 # Special handling for staticmethod/classmethod.
969 if isinstance(val, staticmethod):
970 val = getattr(obj, valname)
971 if isinstance(val, classmethod):
972 val = getattr(obj, valname).im_func
973
974 # Recurse to methods, properties, and nested classes.
975 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +0000976 isinstance(val, property)) and
977 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000978 valname = '%s.%s' % (name, valname)
979 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000980 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000981
982 def _get_test(self, obj, name, module, globs, source_lines):
983 """
984 Return a DocTest for the given object, if it defines a docstring;
985 otherwise, return None.
986 """
987 # Extract the object's docstring. If it doesn't have one,
988 # then return None (no test for this object).
989 if isinstance(obj, basestring):
990 docstring = obj
991 else:
992 try:
993 if obj.__doc__ is None:
994 return None
995 docstring = str(obj.__doc__)
996 except (TypeError, AttributeError):
997 return None
998
999 # Don't bother if the docstring is empty.
1000 if not docstring:
1001 return None
1002
1003 # Find the docstring's location in the file.
1004 lineno = self._find_lineno(obj, source_lines)
1005
1006 # Return a DocTest for this object.
1007 if module is None:
1008 filename = None
1009 else:
1010 filename = getattr(module, '__file__', module.__name__)
Tim Peters19397e52004-08-06 22:02:59 +00001011 return self._doctest_factory(docstring, globs, name, filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001012
1013 def _find_lineno(self, obj, source_lines):
1014 """
1015 Return a line number of the given object's docstring. Note:
1016 this method assumes that the object has a docstring.
1017 """
1018 lineno = None
1019
1020 # Find the line number for modules.
1021 if inspect.ismodule(obj):
1022 lineno = 0
1023
1024 # Find the line number for classes.
1025 # Note: this could be fooled if a class is defined multiple
1026 # times in a single file.
1027 if inspect.isclass(obj):
1028 if source_lines is None:
1029 return None
1030 pat = re.compile(r'^\s*class\s*%s\b' %
1031 getattr(obj, '__name__', '-'))
1032 for i, line in enumerate(source_lines):
1033 if pat.match(line):
1034 lineno = i
1035 break
1036
1037 # Find the line number for functions & methods.
1038 if inspect.ismethod(obj): obj = obj.im_func
1039 if inspect.isfunction(obj): obj = obj.func_code
1040 if inspect.istraceback(obj): obj = obj.tb_frame
1041 if inspect.isframe(obj): obj = obj.f_code
1042 if inspect.iscode(obj):
1043 lineno = getattr(obj, 'co_firstlineno', None)-1
1044
1045 # Find the line number where the docstring starts. Assume
1046 # that it's the first line that begins with a quote mark.
1047 # Note: this could be fooled by a multiline function
1048 # signature, where a continuation line begins with a quote
1049 # mark.
1050 if lineno is not None:
1051 if source_lines is None:
1052 return lineno+1
1053 pat = re.compile('(^|.*:)\s*\w*("|\')')
1054 for lineno in range(lineno, len(source_lines)):
1055 if pat.match(source_lines[lineno]):
1056 return lineno
1057
1058 # We couldn't find the line number.
1059 return None
1060
1061######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001062## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001063######################################################################
1064
1065# [XX] Should overridable methods (eg DocTestRunner.check_output) be
1066# named with a leading underscore?
1067
1068class DocTestRunner:
1069 """
1070 A class used to run DocTest test cases, and accumulate statistics.
1071 The `run` method is used to process a single DocTest case. It
1072 returns a tuple `(f, t)`, where `t` is the number of test cases
1073 tried, and `f` is the number of test cases that failed.
1074
1075 >>> tests = DocTestFinder().find(_TestClass)
1076 >>> runner = DocTestRunner(verbose=False)
1077 >>> for test in tests:
1078 ... print runner.run(test)
1079 (0, 2)
1080 (0, 1)
1081 (0, 2)
1082 (0, 2)
1083
1084 The `summarize` method prints a summary of all the test cases that
1085 have been run by the runner, and returns an aggregated `(f, t)`
1086 tuple:
1087
1088 >>> runner.summarize(verbose=1)
1089 4 items passed all tests:
1090 2 tests in _TestClass
1091 2 tests in _TestClass.__init__
1092 2 tests in _TestClass.get
1093 1 tests in _TestClass.square
1094 7 tests in 4 items.
1095 7 passed and 0 failed.
1096 Test passed.
1097 (0, 7)
1098
1099 The aggregated number of tried examples and failed examples is
1100 also available via the `tries` and `failures` attributes:
1101
1102 >>> runner.tries
1103 7
1104 >>> runner.failures
1105 0
1106
1107 The comparison between expected outputs and actual outputs is done
1108 by the `check_output` method. This comparison may be customized
1109 with a number of option flags; see the documentation for `testmod`
1110 for more information. If the option flags are insufficient, then
1111 the comparison may also be customized by subclassing
1112 DocTestRunner, and overriding the methods `check_output` and
1113 `output_difference`.
1114
1115 The test runner's display output can be controlled in two ways.
1116 First, an output function (`out) can be passed to
1117 `TestRunner.run`; this function will be called with strings that
1118 should be displayed. It defaults to `sys.stdout.write`. If
1119 capturing the output is not sufficient, then the display output
1120 can be also customized by subclassing DocTestRunner, and
1121 overriding the methods `report_start`, `report_success`,
1122 `report_unexpected_exception`, and `report_failure`.
1123 """
1124 # This divider string is used to separate failure messages, and to
1125 # separate sections of the summary.
1126 DIVIDER = "*" * 70
1127
1128 def __init__(self, verbose=None, optionflags=0):
1129 """
1130 Create a new test runner.
1131
1132 Optional keyword arg 'verbose' prints lots of stuff if true,
1133 only failures if false; by default, it's true iff '-v' is in
1134 sys.argv.
1135
1136 Optional argument `optionflags` can be used to control how the
1137 test runner compares expected output to actual output, and how
1138 it displays failures. See the documentation for `testmod` for
1139 more information.
1140 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001141 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001142 verbose = '-v' in sys.argv
1143 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001144 self.optionflags = optionflags
1145
Tim Peters8485b562004-08-04 18:46:34 +00001146 # Keep track of the examples we've run.
1147 self.tries = 0
1148 self.failures = 0
1149 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001150
Tim Peters8485b562004-08-04 18:46:34 +00001151 # Create a fake output target for capturing doctest output.
1152 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001153
Tim Peters8485b562004-08-04 18:46:34 +00001154 #/////////////////////////////////////////////////////////////////
1155 # Output verification methods
1156 #/////////////////////////////////////////////////////////////////
1157 # These two methods should be updated together, since the
1158 # output_difference method needs to know what should be considered
1159 # to match by check_output.
1160
1161 def check_output(self, want, got):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001162 """
Tim Peters8485b562004-08-04 18:46:34 +00001163 Return True iff the actual output (`got`) matches the expected
1164 output (`want`). These strings are always considered to match
1165 if they are identical; but depending on what option flags the
1166 test runner is using, several non-exact match types are also
1167 possible. See the documentation for `TestRunner` for more
1168 information about option flags.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001169 """
Tim Peters8485b562004-08-04 18:46:34 +00001170 # Handle the common case first, for efficiency:
1171 # if they're string-identical, always return true.
1172 if got == want:
1173 return True
Tim Peters8a7d2d52001-01-16 07:10:57 +00001174
Tim Peters8485b562004-08-04 18:46:34 +00001175 # The values True and False replaced 1 and 0 as the return
1176 # value for boolean comparisons in Python 2.3.
1177 if not (self.optionflags & DONT_ACCEPT_TRUE_FOR_1):
1178 if (got,want) == ("True\n", "1\n"):
1179 return True
1180 if (got,want) == ("False\n", "0\n"):
1181 return True
Tim Peters8a7d2d52001-01-16 07:10:57 +00001182
Tim Peters8485b562004-08-04 18:46:34 +00001183 # <BLANKLINE> can be used as a special sequence to signify a
1184 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1185 if not (self.optionflags & DONT_ACCEPT_BLANKLINE):
1186 # Replace <BLANKLINE> in want with a blank line.
1187 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1188 '', want)
1189 # If a line in got contains only spaces, then remove the
1190 # spaces.
1191 got = re.sub('(?m)^\s*?$', '', got)
1192 if got == want:
1193 return True
1194
1195 # This flag causes doctest to ignore any differences in the
1196 # contents of whitespace strings. Note that this can be used
1197 # in conjunction with the ELLISPIS flag.
1198 if (self.optionflags & NORMALIZE_WHITESPACE):
1199 got = ' '.join(got.split())
1200 want = ' '.join(want.split())
1201 if got == want:
1202 return True
1203
1204 # The ELLIPSIS flag says to let the sequence "..." in `want`
1205 # match any substring in `got`. We implement this by
1206 # transforming `want` into a regular expression.
1207 if (self.optionflags & ELLIPSIS):
1208 # Escape any special regexp characters
1209 want_re = re.escape(want)
1210 # Replace ellipsis markers ('...') with .*
1211 want_re = want_re.replace(re.escape(ELLIPSIS_MARKER), '.*')
1212 # Require that it matches the entire string; and set the
1213 # re.DOTALL flag (with '(?s)').
1214 want_re = '(?s)^%s$' % want_re
1215 # Check if the `want_re` regexp matches got.
1216 if re.match(want_re, got):
1217 return True
1218
1219 # We didn't find any match; return false.
1220 return False
1221
1222 def output_difference(self, want, got):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001223 """
Tim Peters8485b562004-08-04 18:46:34 +00001224 Return a string describing the differences between the
1225 expected output (`want`) and the actual output (`got`).
Tim Peters8a7d2d52001-01-16 07:10:57 +00001226 """
Tim Peters8485b562004-08-04 18:46:34 +00001227 # If <BLANKLINE>s are being used, then replace <BLANKLINE>
1228 # with blank lines in the expected output string.
1229 if not (self.optionflags & DONT_ACCEPT_BLANKLINE):
1230 want = re.sub('(?m)^%s$' % re.escape(BLANKLINE_MARKER), '', want)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001231
Tim Peters8485b562004-08-04 18:46:34 +00001232 # Check if we should use diff. Don't use diff if the actual
1233 # or expected outputs are too short, or if the expected output
1234 # contains an ellipsis marker.
1235 if ((self.optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and
1236 want.count('\n') > 2 and got.count('\n') > 2 and
1237 not (self.optionflags & ELLIPSIS and '...' in want)):
1238 # Split want & got into lines.
1239 want_lines = [l+'\n' for l in want.split('\n')]
1240 got_lines = [l+'\n' for l in got.split('\n')]
1241 # Use difflib to find their differences.
1242 if self.optionflags & UNIFIED_DIFF:
1243 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1244 fromfile='Expected', tofile='Got')
1245 kind = 'unified'
1246 elif self.optionflags & CONTEXT_DIFF:
1247 diff = difflib.context_diff(want_lines, got_lines, n=2,
1248 fromfile='Expected', tofile='Got')
1249 kind = 'context'
1250 else:
1251 assert 0, 'Bad diff option'
1252 # Remove trailing whitespace on diff output.
1253 diff = [line.rstrip() + '\n' for line in diff]
1254 return _tag_msg("Differences (" + kind + " diff)",
1255 ''.join(diff))
Tim Peters17111f32001-10-03 04:08:26 +00001256
Tim Peters8485b562004-08-04 18:46:34 +00001257 # If we're not using diff, then simply list the expected
1258 # output followed by the actual output.
1259 return (_tag_msg("Expected", want or "Nothing") +
1260 _tag_msg("Got", got))
Tim Peters17111f32001-10-03 04:08:26 +00001261
Tim Peters8485b562004-08-04 18:46:34 +00001262 #/////////////////////////////////////////////////////////////////
1263 # Reporting methods
1264 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001265
Tim Peters8485b562004-08-04 18:46:34 +00001266 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001267 """
Tim Peters8485b562004-08-04 18:46:34 +00001268 Report that the test runner is about to process the given
1269 example. (Only displays a message if verbose=True)
1270 """
1271 if self._verbose:
1272 out(_tag_msg("Trying", example.source) +
1273 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001274
Tim Peters8485b562004-08-04 18:46:34 +00001275 def report_success(self, out, test, example, got):
1276 """
1277 Report that the given example ran successfully. (Only
1278 displays a message if verbose=True)
1279 """
1280 if self._verbose:
1281 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001282
Tim Peters8485b562004-08-04 18:46:34 +00001283 def report_failure(self, out, test, example, got):
1284 """
1285 Report that the given example failed.
1286 """
1287 # Print an error message.
1288 out(self.__failure_header(test, example) +
1289 self.output_difference(example.want, got))
Tim Peters7402f792001-10-02 03:53:41 +00001290
Tim Peters8485b562004-08-04 18:46:34 +00001291 def report_unexpected_exception(self, out, test, example, exc_info):
1292 """
1293 Report that the given example raised an unexpected exception.
1294 """
1295 # Get a traceback message.
1296 excout = StringIO()
1297 exc_type, exc_val, exc_tb = exc_info
1298 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
1299 exception_tb = excout.getvalue()
1300 # Print an error message.
1301 out(self.__failure_header(test, example) +
1302 _tag_msg("Exception raised", exception_tb))
Tim Peters7402f792001-10-02 03:53:41 +00001303
Tim Peters8485b562004-08-04 18:46:34 +00001304 def __failure_header(self, test, example):
1305 s = (self.DIVIDER + "\n" +
1306 _tag_msg("Failure in example", example.source))
1307 if test.filename is None:
1308 # [XX] I'm not putting +1 here, to give the same output
1309 # as the old version. But I think it *should* go here.
1310 return s + ("from line #%s of %s\n" %
1311 (example.lineno, test.name))
1312 elif test.lineno is None:
1313 return s + ("from line #%s of %s in %s\n" %
1314 (example.lineno+1, test.name, test.filename))
1315 else:
1316 lineno = test.lineno+example.lineno+1
1317 return s + ("from line #%s of %s (%s)\n" %
1318 (lineno, test.filename, test.name))
Tim Peters7402f792001-10-02 03:53:41 +00001319
Tim Peters8485b562004-08-04 18:46:34 +00001320 #/////////////////////////////////////////////////////////////////
1321 # DocTest Running
1322 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001323
Tim Peters8485b562004-08-04 18:46:34 +00001324 # A regular expression for handling `want` strings that contain
1325 # expected exceptions. It divides `want` into two pieces: the
1326 # pre-exception output (`out`) and the exception message (`exc`),
1327 # as generated by traceback.format_exception_only(). (I assume
1328 # that the exception_only message is the first non-indented line
1329 # starting with word characters after the "Traceback ...".)
1330 _EXCEPTION_RE = re.compile(('^(?P<out>.*)'
1331 '^(?P<hdr>Traceback \((?:%s|%s)\):)\s*$.*?'
1332 '^(?P<exc>\w+.*)') %
1333 ('most recent call last', 'innermost last'),
1334 re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001335
Tim Peters8485b562004-08-04 18:46:34 +00001336 _OPTION_DIRECTIVE_RE = re.compile('\s*doctest:\s*(?P<flags>[^#\n]*)')
Tim Peters7402f792001-10-02 03:53:41 +00001337
Tim Peters8485b562004-08-04 18:46:34 +00001338 def __handle_directive(self, example):
1339 """
1340 Check if the given example is actually a directive to doctest
1341 (to turn an optionflag on or off); and if it is, then handle
1342 the directive.
Tim Peters7402f792001-10-02 03:53:41 +00001343
Tim Peters8485b562004-08-04 18:46:34 +00001344 Return true iff the example is actually a directive (and so
1345 should not be executed).
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001346
Tim Peters8a7d2d52001-01-16 07:10:57 +00001347 """
Tim Peters8485b562004-08-04 18:46:34 +00001348 m = self._OPTION_DIRECTIVE_RE.match(example.source)
1349 if m is None:
1350 return False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001351
Tim Peters8485b562004-08-04 18:46:34 +00001352 for flag in m.group('flags').upper().split():
1353 if (flag[:1] not in '+-' or
1354 flag[1:] not in OPTIONFLAGS_BY_NAME):
1355 raise ValueError('Bad doctest option directive: '+flag)
1356 if flag[0] == '+':
1357 self.optionflags |= OPTIONFLAGS_BY_NAME[flag[1:]]
1358 else:
1359 self.optionflags &= ~OPTIONFLAGS_BY_NAME[flag[1:]]
1360 return True
Tim Peters8a7d2d52001-01-16 07:10:57 +00001361
Tim Peters8485b562004-08-04 18:46:34 +00001362 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001363 """
Tim Peters8485b562004-08-04 18:46:34 +00001364 Run the examples in `test`. Write the outcome of each example
1365 with one of the `DocTestRunner.report_*` methods, using the
1366 writer function `out`. `compileflags` is the set of compiler
1367 flags that should be used to execute examples. Return a tuple
1368 `(f, t)`, where `t` is the number of examples tried, and `f`
1369 is the number of examples that failed. The examples are run
1370 in the namespace `test.globs`.
1371 """
1372 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001373 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001374
1375 # Save the option flags (since option directives can be used
1376 # to modify them).
1377 original_optionflags = self.optionflags
1378
1379 # Process each example.
1380 for example in test.examples:
1381 # Check if it's an option directive. If it is, then handle
1382 # it, and go on to the next example.
1383 if self.__handle_directive(example):
1384 continue
1385
1386 # Record that we started this example.
1387 tries += 1
1388 self.report_start(out, test, example)
1389
1390 # Run the example in the given context (globs), and record
1391 # any exception that gets raised. (But don't intercept
1392 # keyboard interrupts.)
1393 try:
1394 # If the example is a compound statement on one line,
1395 # like "if 1: print 2", then compile() requires a
1396 # trailing newline. Rather than analyze that, always
1397 # append one (it never hurts).
1398 exec compile(example.source + '\n', "<string>", "single",
1399 compileflags, 1) in test.globs
1400 exception = None
1401 except KeyboardInterrupt:
1402 raise
1403 except:
1404 exception = sys.exc_info()
1405
1406 # Extract the example's actual output from fakeout, and
1407 # write it to `got`. Add a terminating newline if it
1408 # doesn't have already one.
1409 got = self._fakeout.getvalue()
1410 self._fakeout.truncate(0)
1411
1412 # If the example executed without raising any exceptions,
1413 # then verify its output and report its outcome.
1414 if exception is None:
1415 if self.check_output(example.want, got):
1416 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001417 else:
Tim Peters8485b562004-08-04 18:46:34 +00001418 self.report_failure(out, test, example, got)
1419 failures += 1
1420
1421 # If the example raised an exception, then check if it was
1422 # expected.
1423 else:
1424 exc_info = sys.exc_info()
1425 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1426
1427 # Search the `want` string for an exception. If we don't
1428 # find one, then report an unexpected exception.
1429 m = self._EXCEPTION_RE.match(example.want)
1430 if m is None:
1431 self.report_unexpected_exception(out, test, example,
1432 exc_info)
1433 failures += 1
1434 else:
1435 exc_hdr = m.group('hdr')+'\n' # Exception header
1436 # The test passes iff the pre-exception output and
1437 # the exception description match the values given
1438 # in `want`.
1439 if (self.check_output(m.group('out'), got) and
1440 self.check_output(m.group('exc'), exc_msg)):
1441 # Is +exc_msg the right thing here??
1442 self.report_success(out, test, example,
1443 got+exc_hdr+exc_msg)
1444 else:
1445 self.report_failure(out, test, example,
1446 got+exc_hdr+exc_msg)
1447 failures += 1
1448
1449 # Restore the option flags (in case they were modified)
1450 self.optionflags = original_optionflags
1451
1452 # Record and return the number of failures and tries.
1453 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001454 return failures, tries
1455
Tim Peters8485b562004-08-04 18:46:34 +00001456 def __record_outcome(self, test, f, t):
1457 """
1458 Record the fact that the given DocTest (`test`) generated `f`
1459 failures out of `t` tried examples.
1460 """
1461 f2, t2 = self._name2ft.get(test.name, (0,0))
1462 self._name2ft[test.name] = (f+f2, t+t2)
1463 self.failures += f
1464 self.tries += t
1465
1466 def run(self, test, compileflags=None, out=None, clear_globs=True):
1467 """
1468 Run the examples in `test`, and display the results using the
1469 writer function `out`.
1470
1471 The examples are run in the namespace `test.globs`. If
1472 `clear_globs` is true (the default), then this namespace will
1473 be cleared after the test runs, to help with garbage
1474 collection. If you would like to examine the namespace after
1475 the test completes, then use `clear_globs=False`.
1476
1477 `compileflags` gives the set of flags that should be used by
1478 the Python compiler when running the examples. If not
1479 specified, then it will default to the set of future-import
1480 flags that apply to `globs`.
1481
1482 The output of each example is checked using
1483 `DocTestRunner.check_output`, and the results are formatted by
1484 the `DocTestRunner.report_*` methods.
1485 """
1486 if compileflags is None:
1487 compileflags = _extract_future_flags(test.globs)
1488 if out is None:
1489 out = sys.stdout.write
1490 saveout = sys.stdout
1491
1492 try:
1493 sys.stdout = self._fakeout
1494 return self.__run(test, compileflags, out)
1495 finally:
1496 sys.stdout = saveout
Tim Peters8485b562004-08-04 18:46:34 +00001497 if clear_globs:
1498 test.globs.clear()
1499
1500 #/////////////////////////////////////////////////////////////////
1501 # Summarization
1502 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001503 def summarize(self, verbose=None):
1504 """
Tim Peters8485b562004-08-04 18:46:34 +00001505 Print a summary of all the test cases that have been run by
1506 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1507 the total number of failed examples, and `t` is the total
1508 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001509
Tim Peters8485b562004-08-04 18:46:34 +00001510 The optional `verbose` argument controls how detailed the
1511 summary is. If the verbosity is not specified, then the
1512 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001513 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001514 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001515 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001516 notests = []
1517 passed = []
1518 failed = []
1519 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001520 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001521 name, (f, t) = x
1522 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001523 totalt += t
1524 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001525 if t == 0:
1526 notests.append(name)
1527 elif f == 0:
1528 passed.append( (name, t) )
1529 else:
1530 failed.append(x)
1531 if verbose:
1532 if notests:
1533 print len(notests), "items had no tests:"
1534 notests.sort()
1535 for thing in notests:
1536 print " ", thing
1537 if passed:
1538 print len(passed), "items passed all tests:"
1539 passed.sort()
1540 for thing, count in passed:
1541 print " %3d tests in %s" % (count, thing)
1542 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001543 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001544 print len(failed), "items had failures:"
1545 failed.sort()
1546 for thing, (f, t) in failed:
1547 print " %3d of %3d in %s" % (f, t, thing)
1548 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001549 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001550 print totalt - totalf, "passed and", totalf, "failed."
1551 if totalf:
1552 print "***Test Failed***", totalf, "failures."
1553 elif verbose:
1554 print "Test passed."
1555 return totalf, totalt
1556
Tim Peters19397e52004-08-06 22:02:59 +00001557class DocTestFailure(Exception):
1558 """A DocTest example has failed in debugging mode.
1559
1560 The exception instance has variables:
1561
1562 - test: the DocTest object being run
1563
1564 - excample: the Example object that failed
1565
1566 - got: the actual output
1567 """
1568 def __init__(self, test, example, got):
1569 self.test = test
1570 self.example = example
1571 self.got = got
1572
1573 def __str__(self):
1574 return str(self.test)
1575
1576class UnexpectedException(Exception):
1577 """A DocTest example has encountered an unexpected exception
1578
1579 The exception instance has variables:
1580
1581 - test: the DocTest object being run
1582
1583 - excample: the Example object that failed
1584
1585 - exc_info: the exception info
1586 """
1587 def __init__(self, test, example, exc_info):
1588 self.test = test
1589 self.example = example
1590 self.exc_info = exc_info
1591
1592 def __str__(self):
1593 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001594
Tim Peters19397e52004-08-06 22:02:59 +00001595class DebugRunner(DocTestRunner):
1596 r"""Run doc tests but raise an exception as soon as there is a failure.
1597
1598 If an unexpected exception occurs, an UnexpectedException is raised.
1599 It contains the test, the example, and the original exception:
1600
1601 >>> runner = DebugRunner(verbose=False)
1602 >>> test = DocTest('>>> raise KeyError\n42', {}, 'foo', 'foo.py', 0)
1603 >>> try:
1604 ... runner.run(test)
1605 ... except UnexpectedException, failure:
1606 ... pass
1607
1608 >>> failure.test is test
1609 True
1610
1611 >>> failure.example.want
1612 '42\n'
1613
1614 >>> exc_info = failure.exc_info
1615 >>> raise exc_info[0], exc_info[1], exc_info[2]
1616 Traceback (most recent call last):
1617 ...
1618 KeyError
1619
1620 We wrap the original exception to give the calling application
1621 access to the test and example information.
1622
1623 If the output doesn't match, then a DocTestFailure is raised:
1624
1625 >>> test = DocTest('''
1626 ... >>> x = 1
1627 ... >>> x
1628 ... 2
1629 ... ''', {}, 'foo', 'foo.py', 0)
1630
1631 >>> try:
1632 ... runner.run(test)
1633 ... except DocTestFailure, failure:
1634 ... pass
1635
1636 DocTestFailure objects provide access to the test:
1637
1638 >>> failure.test is test
1639 True
1640
1641 As well as to the example:
1642
1643 >>> failure.example.want
1644 '2\n'
1645
1646 and the actual output:
1647
1648 >>> failure.got
1649 '1\n'
1650
1651 If a failure or error occurs, the globals are left intact:
1652
1653 >>> del test.globs['__builtins__']
1654 >>> test.globs
1655 {'x': 1}
1656
1657 >>> test = DocTest('''
1658 ... >>> x = 2
1659 ... >>> raise KeyError
1660 ... ''', {}, 'foo', 'foo.py', 0)
1661
1662 >>> runner.run(test)
1663 Traceback (most recent call last):
1664 ...
1665 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001666
Tim Peters19397e52004-08-06 22:02:59 +00001667 >>> del test.globs['__builtins__']
1668 >>> test.globs
1669 {'x': 2}
1670
1671 But the globals are cleared if there is no error:
1672
1673 >>> test = DocTest('''
1674 ... >>> x = 2
1675 ... ''', {}, 'foo', 'foo.py', 0)
1676
1677 >>> runner.run(test)
1678 (0, 1)
1679
1680 >>> test.globs
1681 {}
1682
1683 """
1684
1685 def run(self, test, compileflags=None, out=None, clear_globs=True):
1686 r = DocTestRunner.run(self, test, compileflags, out, False)
1687 if clear_globs:
1688 test.globs.clear()
1689 return r
1690
1691 def report_unexpected_exception(self, out, test, example, exc_info):
1692 raise UnexpectedException(test, example, exc_info)
1693
1694 def report_failure(self, out, test, example, got):
1695 raise DocTestFailure(test, example, got)
1696
Tim Peters8485b562004-08-04 18:46:34 +00001697######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001698## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001699######################################################################
1700# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001701
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001702def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001703 report=True, optionflags=0, extraglobs=None,
1704 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001705 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001706 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001707
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001708 Test examples in docstrings in functions and classes reachable
1709 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001710 with m.__doc__. Unless isprivate is specified, private names
1711 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001712
1713 Also test examples reachable from dict m.__test__ if it exists and is
1714 not None. m.__dict__ maps names to functions, classes and strings;
1715 function and class docstrings are tested even if the name is private;
1716 strings are tested directly, as if they were docstrings.
1717
1718 Return (#failures, #tests).
1719
1720 See doctest.__doc__ for an overview.
1721
1722 Optional keyword arg "name" gives the name of the module; by default
1723 use m.__name__.
1724
1725 Optional keyword arg "globs" gives a dict to be used as the globals
1726 when executing examples; by default, use m.__dict__. A copy of this
1727 dict is actually used for each docstring, so that each docstring's
1728 examples start with a clean slate.
1729
Tim Peters8485b562004-08-04 18:46:34 +00001730 Optional keyword arg "extraglobs" gives a dictionary that should be
1731 merged into the globals that are used to execute examples. By
1732 default, no extra globals are used. This is new in 2.4.
1733
Tim Peters8a7d2d52001-01-16 07:10:57 +00001734 Optional keyword arg "verbose" prints lots of stuff if true, prints
1735 only failures if false; by default, it's true iff "-v" is in sys.argv.
1736
Tim Peters8a7d2d52001-01-16 07:10:57 +00001737 Optional keyword arg "report" prints a summary at the end when true,
1738 else prints nothing at the end. In verbose mode, the summary is
1739 detailed, else very brief (in fact, empty if all tests passed).
1740
Tim Peters6ebe61f2003-06-27 20:48:05 +00001741 Optional keyword arg "optionflags" or's together module constants,
1742 and defaults to 0. This is new in 2.3. Possible values:
1743
1744 DONT_ACCEPT_TRUE_FOR_1
1745 By default, if an expected output block contains just "1",
1746 an actual output block containing just "True" is considered
1747 to be a match, and similarly for "0" versus "False". When
1748 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1749 is allowed.
1750
Tim Peters8485b562004-08-04 18:46:34 +00001751 DONT_ACCEPT_BLANKLINE
1752 By default, if an expected output block contains a line
1753 containing only the string "<BLANKLINE>", then that line
1754 will match a blank line in the actual output. When
1755 DONT_ACCEPT_BLANKLINE is specified, this substitution is
1756 not allowed.
1757
1758 NORMALIZE_WHITESPACE
1759 When NORMALIZE_WHITESPACE is specified, all sequences of
1760 whitespace are treated as equal. I.e., any sequence of
1761 whitespace within the expected output will match any
1762 sequence of whitespace within the actual output.
1763
1764 ELLIPSIS
1765 When ELLIPSIS is specified, then an ellipsis marker
1766 ("...") in the expected output can match any substring in
1767 the actual output.
1768
1769 UNIFIED_DIFF
1770 When UNIFIED_DIFF is specified, failures that involve
1771 multi-line expected and actual outputs will be displayed
1772 using a unified diff.
1773
1774 CONTEXT_DIFF
1775 When CONTEXT_DIFF is specified, failures that involve
1776 multi-line expected and actual outputs will be displayed
1777 using a context diff.
Tim Peters19397e52004-08-06 22:02:59 +00001778
1779 Optional keyword arg "raise_on_error" raises an exception on the
1780 first unexpected exception or failure. This allows failures to be
1781 post-mortem debugged.
1782
Tim Petersf727c6c2004-08-08 01:48:59 +00001783 Deprecated in Python 2.4:
1784 Optional keyword arg "isprivate" specifies a function used to
1785 determine whether a name is private. The default function is
1786 treat all functions as public. Optionally, "isprivate" can be
1787 set to doctest.is_private to skip over functions marked as private
1788 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001789 """
1790
1791 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001792 Advanced tomfoolery: testmod runs methods of a local instance of
1793 class doctest.Tester, then merges the results into (or creates)
1794 global Tester instance doctest.master. Methods of doctest.master
1795 can be called directly too, if you want to do something unusual.
1796 Passing report=0 to testmod is especially useful then, to delay
1797 displaying a summary. Invoke doctest.master.summarize(verbose)
1798 when you're done fiddling.
1799 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001800 if isprivate is not None:
1801 warnings.warn("the isprivate argument is deprecated; "
1802 "examine DocTestFinder.find() lists instead",
1803 DeprecationWarning)
1804
Tim Peters8485b562004-08-04 18:46:34 +00001805 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001806 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001807 # DWA - m will still be None if this wasn't invoked from the command
1808 # line, in which case the following TypeError is about as good an error
1809 # as we should expect
1810 m = sys.modules.get('__main__')
1811
Tim Peters8485b562004-08-04 18:46:34 +00001812 # Check that we were actually given a module.
1813 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001814 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001815
1816 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001817 if name is None:
1818 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001819
1820 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001821 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001822
1823 if raise_on_error:
1824 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1825 else:
1826 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1827
Tim Peters8485b562004-08-04 18:46:34 +00001828 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1829 runner.run(test)
1830
Tim Peters8a7d2d52001-01-16 07:10:57 +00001831 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001832 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001833
Tim Peters8485b562004-08-04 18:46:34 +00001834 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001835
Tim Peters8485b562004-08-04 18:46:34 +00001836def run_docstring_examples(f, globs, verbose=False, name="NoName",
1837 compileflags=None, optionflags=0):
1838 """
1839 Test examples in the given object's docstring (`f`), using `globs`
1840 as globals. Optional argument `name` is used in failure messages.
1841 If the optional argument `verbose` is true, then generate output
1842 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001843
Tim Peters8485b562004-08-04 18:46:34 +00001844 `compileflags` gives the set of flags that should be used by the
1845 Python compiler when running the examples. If not specified, then
1846 it will default to the set of future-import flags that apply to
1847 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001848
Tim Peters8485b562004-08-04 18:46:34 +00001849 Optional keyword arg `optionflags` specifies options for the
1850 testing and output. See the documentation for `testmod` for more
1851 information.
1852 """
1853 # Find, parse, and run all tests in the given module.
1854 finder = DocTestFinder(verbose=verbose, recurse=False)
1855 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1856 for test in finder.find(f, name, globs=globs):
1857 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001858
Tim Peters8485b562004-08-04 18:46:34 +00001859######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001860## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001861######################################################################
1862# This is provided only for backwards compatibility. It's not
1863# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001864
Tim Peters8485b562004-08-04 18:46:34 +00001865class Tester:
1866 def __init__(self, mod=None, globs=None, verbose=None,
1867 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001868
1869 warnings.warn("class Tester is deprecated; "
1870 "use class doctest.DocTestRunner instead",
1871 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001872 if mod is None and globs is None:
1873 raise TypeError("Tester.__init__: must specify mod or globs")
1874 if mod is not None and not _ismodule(mod):
1875 raise TypeError("Tester.__init__: mod must be a module; %r" %
1876 (mod,))
1877 if globs is None:
1878 globs = mod.__dict__
1879 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001880
Tim Peters8485b562004-08-04 18:46:34 +00001881 self.verbose = verbose
1882 self.isprivate = isprivate
1883 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001884 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001885 self.testrunner = DocTestRunner(verbose=verbose,
1886 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001887
Tim Peters8485b562004-08-04 18:46:34 +00001888 def runstring(self, s, name):
1889 test = DocTest(s, self.globs, name, None, None)
1890 if self.verbose:
1891 print "Running string", name
1892 (f,t) = self.testrunner.run(test)
1893 if self.verbose:
1894 print f, "of", t, "examples failed in string", name
1895 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001896
Tim Petersf3f57472004-08-08 06:11:48 +00001897 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001898 f = t = 0
1899 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001900 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001901 for test in tests:
1902 (f2, t2) = self.testrunner.run(test)
1903 (f,t) = (f+f2, t+t2)
1904 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001905
Tim Peters8485b562004-08-04 18:46:34 +00001906 def rundict(self, d, name, module=None):
1907 import new
1908 m = new.module(name)
1909 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001910 if module is None:
1911 module = False
1912 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001913
Tim Peters8485b562004-08-04 18:46:34 +00001914 def run__test__(self, d, name):
1915 import new
1916 m = new.module(name)
1917 m.__test__ = d
1918 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001919
Tim Peters8485b562004-08-04 18:46:34 +00001920 def summarize(self, verbose=None):
1921 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001922
Tim Peters8485b562004-08-04 18:46:34 +00001923 def merge(self, other):
1924 d = self.testrunner._name2ft
1925 for name, (f, t) in other.testrunner._name2ft.items():
1926 if name in d:
1927 print "*** Tester.merge: '" + name + "' in both" \
1928 " testers; summing outcomes."
1929 f2, t2 = d[name]
1930 f = f + f2
1931 t = t + t2
1932 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001933
Tim Peters8485b562004-08-04 18:46:34 +00001934######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001935## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001936######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001937
Tim Peters19397e52004-08-06 22:02:59 +00001938class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001939
Tim Peters19397e52004-08-06 22:02:59 +00001940 def __init__(self, test, optionflags=0, setUp=None, tearDown=None):
Jim Fultona643b652004-07-14 19:06:50 +00001941 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00001942 self._dt_optionflags = optionflags
1943 self._dt_test = test
1944 self._dt_setUp = setUp
1945 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00001946
Jim Fultona643b652004-07-14 19:06:50 +00001947 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00001948 if self._dt_setUp is not None:
1949 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00001950
1951 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00001952 if self._dt_tearDown is not None:
1953 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00001954
1955 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00001956 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00001957 old = sys.stdout
1958 new = StringIO()
Tim Peters19397e52004-08-06 22:02:59 +00001959 runner = DocTestRunner(optionflags=self._dt_optionflags, verbose=False)
1960
Jim Fultona643b652004-07-14 19:06:50 +00001961 try:
Tim Peters19397e52004-08-06 22:02:59 +00001962 runner.DIVIDER = "-"*70
1963 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00001964 finally:
1965 sys.stdout = old
1966
1967 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00001968 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00001969
Tim Peters19397e52004-08-06 22:02:59 +00001970 def format_failure(self, err):
1971 test = self._dt_test
1972 if test.lineno is None:
1973 lineno = 'unknown line number'
1974 else:
1975 lineno = 'line %s' % test.lineno
1976 lname = '.'.join(test.name.split('.')[-1:])
1977 return ('Failed doctest test for %s\n'
1978 ' File "%s", line %s, in %s\n\n%s'
1979 % (test.name, test.filename, lineno, lname, err)
1980 )
1981
1982 def debug(self):
1983 r"""Run the test case without results and without catching exceptions
1984
1985 The unit test framework includes a debug method on test cases
1986 and test suites to support post-mortem debugging. The test code
1987 is run in such a way that errors are not caught. This way a
1988 caller can catch the errors and initiate post-mortem debugging.
1989
1990 The DocTestCase provides a debug method that raises
1991 UnexpectedException errors if there is an unexepcted
1992 exception:
1993
1994 >>> test = DocTest('>>> raise KeyError\n42',
1995 ... {}, 'foo', 'foo.py', 0)
1996 >>> case = DocTestCase(test)
1997 >>> try:
1998 ... case.debug()
1999 ... except UnexpectedException, failure:
2000 ... pass
2001
2002 The UnexpectedException contains the test, the example, and
2003 the original exception:
2004
2005 >>> failure.test is test
2006 True
2007
2008 >>> failure.example.want
2009 '42\n'
2010
2011 >>> exc_info = failure.exc_info
2012 >>> raise exc_info[0], exc_info[1], exc_info[2]
2013 Traceback (most recent call last):
2014 ...
2015 KeyError
2016
2017 If the output doesn't match, then a DocTestFailure is raised:
2018
2019 >>> test = DocTest('''
2020 ... >>> x = 1
2021 ... >>> x
2022 ... 2
2023 ... ''', {}, 'foo', 'foo.py', 0)
2024 >>> case = DocTestCase(test)
2025
2026 >>> try:
2027 ... case.debug()
2028 ... except DocTestFailure, failure:
2029 ... pass
2030
2031 DocTestFailure objects provide access to the test:
2032
2033 >>> failure.test is test
2034 True
2035
2036 As well as to the example:
2037
2038 >>> failure.example.want
2039 '2\n'
2040
2041 and the actual output:
2042
2043 >>> failure.got
2044 '1\n'
2045
2046 """
2047
2048 runner = DebugRunner(verbose = False, optionflags=self._dt_optionflags)
2049 runner.run(self._dt_test, out=nooutput)
Jim Fultona643b652004-07-14 19:06:50 +00002050
2051 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002052 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002053
2054 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002055 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002056 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2057
2058 __str__ = __repr__
2059
2060 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002061 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002062
Tim Peters19397e52004-08-06 22:02:59 +00002063def nooutput(*args):
2064 pass
Jim Fultona643b652004-07-14 19:06:50 +00002065
Tim Peters19397e52004-08-06 22:02:59 +00002066def DocTestSuite(module=None, globs=None, extraglobs=None,
2067 optionflags=0, test_finder=None,
Tim Peters8485b562004-08-04 18:46:34 +00002068 setUp=lambda: None, tearDown=lambda: None):
2069 """
Tim Peters19397e52004-08-06 22:02:59 +00002070 Convert doctest tests for a mudule to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002071
Tim Peters19397e52004-08-06 22:02:59 +00002072 This converts each documentation string in a module that
2073 contains doctest tests to a unittest test case. If any of the
2074 tests in a doc string fail, then the test case fails. An exception
2075 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002076 (sometimes approximate) line number.
2077
Tim Peters19397e52004-08-06 22:02:59 +00002078 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002079 can be either a module or a module name.
2080
2081 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002082 """
Jim Fultona643b652004-07-14 19:06:50 +00002083
Tim Peters8485b562004-08-04 18:46:34 +00002084 if test_finder is None:
2085 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002086
Tim Peters19397e52004-08-06 22:02:59 +00002087 module = _normalize_module(module)
2088 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2089 if globs is None:
2090 globs = module.__dict__
2091 if not tests: # [XX] why do we want to do this?
2092 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002093
2094 tests.sort()
2095 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002096 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002097 if len(test.examples) == 0:
2098 continue
Tim Peters8485b562004-08-04 18:46:34 +00002099 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002100 filename = module.__file__
2101 if filename.endswith(".pyc"):
2102 filename = filename[:-1]
2103 elif filename.endswith(".pyo"):
2104 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002105 test.filename = filename
Tim Peters19397e52004-08-06 22:02:59 +00002106 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown))
2107
2108 return suite
2109
2110class DocFileCase(DocTestCase):
2111
2112 def id(self):
2113 return '_'.join(self._dt_test.name.split('.'))
2114
2115 def __repr__(self):
2116 return self._dt_test.filename
2117 __str__ = __repr__
2118
2119 def format_failure(self, err):
2120 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2121 % (self._dt_test.name, self._dt_test.filename, err)
2122 )
2123
2124def DocFileTest(path, package=None, globs=None,
2125 setUp=None, tearDown=None,
2126 optionflags=0):
2127 package = _normalize_module(package)
2128 name = path.split('/')[-1]
2129 dir = os.path.split(package.__file__)[0]
2130 path = os.path.join(dir, *(path.split('/')))
2131 doc = open(path).read()
2132
2133 if globs is None:
2134 globs = {}
2135
2136 test = DocTest(doc, globs, name, path, 0)
2137
2138 return DocFileCase(test, optionflags, setUp, tearDown)
2139
2140def DocFileSuite(*paths, **kw):
2141 """Creates a suite of doctest files.
2142
2143 One or more text file paths are given as strings. These should
2144 use "/" characters to separate path segments. Paths are relative
2145 to the directory of the calling module, or relative to the package
2146 passed as a keyword argument.
2147
2148 A number of options may be provided as keyword arguments:
2149
2150 package
2151 The name of a Python package. Text-file paths will be
2152 interpreted relative to the directory containing this package.
2153 The package may be supplied as a package object or as a dotted
2154 package name.
2155
2156 setUp
2157 The name of a set-up function. This is called before running the
2158 tests in each file.
2159
2160 tearDown
2161 The name of a tear-down function. This is called after running the
2162 tests in each file.
2163
2164 globs
2165 A dictionary containing initial global variables for the tests.
2166 """
2167 suite = unittest.TestSuite()
2168
2169 # We do this here so that _normalize_module is called at the right
2170 # level. If it were called in DocFileTest, then this function
2171 # would be the caller and we might guess the package incorrectly.
2172 kw['package'] = _normalize_module(kw.get('package'))
2173
2174 for path in paths:
2175 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002176
Tim Petersdb3756d2003-06-29 05:30:48 +00002177 return suite
2178
Tim Peters8485b562004-08-04 18:46:34 +00002179######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002180## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002181######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002182
Tim Peters19397e52004-08-06 22:02:59 +00002183def script_from_examples(s):
2184 r"""Extract script from text with examples.
2185
2186 Converts text with examples to a Python script. Example input is
2187 converted to regular code. Example output and all other words
2188 are converted to comments:
2189
2190 >>> text = '''
2191 ... Here are examples of simple math.
2192 ...
2193 ... Python has super accurate integer addition
2194 ...
2195 ... >>> 2 + 2
2196 ... 5
2197 ...
2198 ... And very friendly error messages:
2199 ...
2200 ... >>> 1/0
2201 ... To Infinity
2202 ... And
2203 ... Beyond
2204 ...
2205 ... You can use logic if you want:
2206 ...
2207 ... >>> if 0:
2208 ... ... blah
2209 ... ... blah
2210 ... ...
2211 ...
2212 ... Ho hum
2213 ... '''
2214
2215 >>> print script_from_examples(text)
2216 # Here are examples of simple math.
2217 #
2218 # Python has super accurate integer addition
2219 #
2220 2 + 2
2221 # Expected:
2222 # 5
2223 #
2224 # And very friendly error messages:
2225 #
2226 1/0
2227 # Expected:
2228 # To Infinity
2229 # And
2230 # Beyond
2231 #
2232 # You can use logic if you want:
2233 #
2234 if 0:
2235 blah
2236 blah
2237 <BLANKLINE>
2238 #
2239 # Ho hum
2240 """
2241
2242 return Parser('<string>', s).get_program()
2243
Tim Peters8485b562004-08-04 18:46:34 +00002244def _want_comment(example):
2245 """
Tim Peters19397e52004-08-06 22:02:59 +00002246 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002247 """
Jim Fultona643b652004-07-14 19:06:50 +00002248 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002249 want = example.want
2250 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002251 if want[-1] == '\n':
2252 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002253 want = "\n# ".join(want.split("\n"))
2254 want = "\n# Expected:\n# %s" % want
2255 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002256
2257def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002258 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002259
2260 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002261 test to be debugged and the name (within the module) of the object
2262 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002263 """
Tim Peters8485b562004-08-04 18:46:34 +00002264 module = _normalize_module(module)
2265 tests = DocTestFinder().find(module)
2266 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002267 if not test:
2268 raise ValueError(name, "not found in tests")
2269 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002270 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002271 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002272
Jim Fultona643b652004-07-14 19:06:50 +00002273def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002274 """Debug a single doctest docstring, in argument `src`'"""
2275 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002276 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002277
Jim Fultona643b652004-07-14 19:06:50 +00002278def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002279 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002280 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002281
Tim Petersdb3756d2003-06-29 05:30:48 +00002282 srcfilename = tempfile.mktemp("doctestdebug.py")
Tim Peters8485b562004-08-04 18:46:34 +00002283 f = open(srcfilename, 'w')
2284 f.write(src)
2285 f.close()
2286
Jim Fultona643b652004-07-14 19:06:50 +00002287 if globs:
2288 globs = globs.copy()
2289 else:
2290 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002291
Tim Peters8485b562004-08-04 18:46:34 +00002292 if pm:
2293 try:
2294 execfile(srcfilename, globs, globs)
2295 except:
2296 print sys.exc_info()[1]
2297 pdb.post_mortem(sys.exc_info()[2])
2298 else:
2299 # Note that %r is vital here. '%s' instead can, e.g., cause
2300 # backslashes to get treated as metacharacters on Windows.
2301 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002302
Jim Fultona643b652004-07-14 19:06:50 +00002303def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002304 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002305
2306 Provide the module (or dotted name of the module) containing the
2307 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002308 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002309 """
Tim Peters8485b562004-08-04 18:46:34 +00002310 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002311 testsrc = testsource(module, name)
2312 debug_script(testsrc, pm, module.__dict__)
2313
Tim Peters8485b562004-08-04 18:46:34 +00002314######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002315## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002316######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002317class _TestClass:
2318 """
2319 A pointless class, for sanity-checking of docstring testing.
2320
2321 Methods:
2322 square()
2323 get()
2324
2325 >>> _TestClass(13).get() + _TestClass(-12).get()
2326 1
2327 >>> hex(_TestClass(13).square().get())
2328 '0xa9'
2329 """
2330
2331 def __init__(self, val):
2332 """val -> _TestClass object with associated value val.
2333
2334 >>> t = _TestClass(123)
2335 >>> print t.get()
2336 123
2337 """
2338
2339 self.val = val
2340
2341 def square(self):
2342 """square() -> square TestClass's associated value
2343
2344 >>> _TestClass(13).square().get()
2345 169
2346 """
2347
2348 self.val = self.val ** 2
2349 return self
2350
2351 def get(self):
2352 """get() -> return TestClass's associated value.
2353
2354 >>> x = _TestClass(-42)
2355 >>> print x.get()
2356 -42
2357 """
2358
2359 return self.val
2360
2361__test__ = {"_TestClass": _TestClass,
2362 "string": r"""
2363 Example of a string object, searched as-is.
2364 >>> x = 1; y = 2
2365 >>> x + y, x * y
2366 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002367 """,
2368 "bool-int equivalence": r"""
2369 In 2.2, boolean expressions displayed
2370 0 or 1. By default, we still accept
2371 them. This can be disabled by passing
2372 DONT_ACCEPT_TRUE_FOR_1 to the new
2373 optionflags argument.
2374 >>> 4 == 4
2375 1
2376 >>> 4 == 4
2377 True
2378 >>> 4 > 4
2379 0
2380 >>> 4 > 4
2381 False
2382 """,
Tim Peters8485b562004-08-04 18:46:34 +00002383 "blank lines": r"""
2384 Blank lines can be marked with <BLANKLINE>:
2385 >>> print 'foo\n\nbar\n'
2386 foo
2387 <BLANKLINE>
2388 bar
2389 <BLANKLINE>
2390 """,
2391 }
2392# "ellipsis": r"""
2393# If the ellipsis flag is used, then '...' can be used to
2394# elide substrings in the desired output:
2395# >>> print range(1000)
2396# [0, 1, 2, ..., 999]
2397# """,
2398# "whitespace normalization": r"""
2399# If the whitespace normalization flag is used, then
2400# differences in whitespace are ignored.
2401# >>> print range(30)
2402# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2403# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2404# 27, 28, 29]
2405# """,
2406# }
2407
2408def test1(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002409>>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2410... "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002411>>> from doctest import Tester
2412>>> t = Tester(globs={'x': 42}, verbose=0)
2413>>> t.runstring(r'''
2414... >>> x = x * 2
2415... >>> print x
2416... 42
2417... ''', 'XYZ')
2418**********************************************************************
2419Failure in example: print x
2420from line #2 of XYZ
2421Expected: 42
2422Got: 84
2423(1, 2)
2424>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2425(0, 2)
2426>>> t.summarize()
2427**********************************************************************
24281 items had failures:
2429 1 of 2 in XYZ
2430***Test Failed*** 1 failures.
2431(1, 4)
2432>>> t.summarize(verbose=1)
24331 items passed all tests:
2434 2 tests in example2
2435**********************************************************************
24361 items had failures:
2437 1 of 2 in XYZ
24384 tests in 2 items.
24393 passed and 1 failed.
2440***Test Failed*** 1 failures.
2441(1, 4)
2442"""
2443
2444def test2(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002445 >>> warnings.filterwarnings("ignore", "class Tester",
2446 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002447 >>> t = Tester(globs={}, verbose=1)
2448 >>> test = r'''
2449 ... # just an example
2450 ... >>> x = 1 + 2
2451 ... >>> x
2452 ... 3
2453 ... '''
2454 >>> t.runstring(test, "Example")
2455 Running string Example
2456 Trying: x = 1 + 2
2457 Expecting: nothing
2458 ok
2459 Trying: x
2460 Expecting: 3
2461 ok
2462 0 of 2 examples failed in string Example
2463 (0, 2)
2464"""
2465def test3(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002466 >>> warnings.filterwarnings("ignore", "class Tester",
2467 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002468 >>> t = Tester(globs={}, verbose=0)
2469 >>> def _f():
2470 ... '''Trivial docstring example.
2471 ... >>> assert 2 == 2
2472 ... '''
2473 ... return 32
2474 ...
2475 >>> t.rundoc(_f) # expect 0 failures in 1 example
2476 (0, 1)
2477"""
2478def test4(): """
2479 >>> import new
2480 >>> m1 = new.module('_m1')
2481 >>> m2 = new.module('_m2')
2482 >>> test_data = \"""
2483 ... def _f():
2484 ... '''>>> assert 1 == 1
2485 ... '''
2486 ... def g():
2487 ... '''>>> assert 2 != 1
2488 ... '''
2489 ... class H:
2490 ... '''>>> assert 2 > 1
2491 ... '''
2492 ... def bar(self):
2493 ... '''>>> assert 1 < 2
2494 ... '''
2495 ... \"""
2496 >>> exec test_data in m1.__dict__
2497 >>> exec test_data in m2.__dict__
2498 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2499
2500 Tests that objects outside m1 are excluded:
2501
Tim Peters3ddd60a2004-08-08 02:43:33 +00002502 >>> warnings.filterwarnings("ignore", "class Tester",
2503 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002504 >>> t = Tester(globs={}, verbose=0)
Tim Petersf727c6c2004-08-08 01:48:59 +00002505 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Tim Peters8485b562004-08-04 18:46:34 +00002506 (0, 4)
2507
Tim Petersf727c6c2004-08-08 01:48:59 +00002508 Once more, not excluding stuff outside m1:
Tim Peters8485b562004-08-04 18:46:34 +00002509
2510 >>> t = Tester(globs={}, verbose=0)
2511 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2512 (0, 8)
2513
2514 The exclusion of objects from outside the designated module is
2515 meant to be invoked automagically by testmod.
2516
Tim Petersf727c6c2004-08-08 01:48:59 +00002517 >>> testmod(m1, verbose=False)
2518 (0, 4)
Tim Peters8485b562004-08-04 18:46:34 +00002519"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002520
2521def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002522 #import doctest
2523 #doctest.testmod(doctest, verbose=False,
2524 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2525 # UNIFIED_DIFF)
2526 #print '~'*70
2527 r = unittest.TextTestRunner()
2528 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002529
2530if __name__ == "__main__":
2531 _test()