blob: 23e1d843ba378f7e88f400d68eb467a5827ff54a [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
Edward Loper78b58f32004-08-09 02:56:02 +0000496 - source: A single python statement, ending in a newline iff the
497 statement spans more than one line.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000498
Edward Loper78b58f32004-08-09 02:56:02 +0000499 - want: The expected output from running the source code (either
500 from stdout, or a traceback in case of exception). `want`
501 should always end with a newline, unless no output is expected,
Tim Peters8a7d2d52001-01-16 07:10:57 +0000502
Tim Peters8485b562004-08-04 18:46:34 +0000503 - lineno: The line number within the DocTest string containing
504 this Example where the Example begins. This line number is
505 zero-based, with respect to the beginning of the DocTest.
506 """
507 def __init__(self, source, want, lineno):
508 # Check invariants.
Tim Peters9b625d32004-08-04 20:04:32 +0000509 if (source[-1:] == '\n') != ('\n' in source[:-1]):
510 raise AssertionError("source must end with newline iff "
511 "source contains more than one line")
512 if want and want[-1] != '\n':
513 raise AssertionError("non-empty want must end with newline")
Tim Peters8485b562004-08-04 18:46:34 +0000514 # Store properties.
515 self.source = source
516 self.want = want
517 self.lineno = lineno
Tim Peters8a7d2d52001-01-16 07:10:57 +0000518
Tim Peters8485b562004-08-04 18:46:34 +0000519class DocTest:
520 """
521 A collection of doctest examples that should be run in a single
522 namespace. Each DocTest defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000523
Tim Peters8485b562004-08-04 18:46:34 +0000524 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000525
Tim Peters8485b562004-08-04 18:46:34 +0000526 - globs: The namespace (aka globals) that the examples should
527 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000528
Tim Peters8485b562004-08-04 18:46:34 +0000529 - name: A name identifying the DocTest (typically, the name of
530 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000531
Tim Peters19397e52004-08-06 22:02:59 +0000532 - docstring: The docstring being tested
533
Tim Peters8485b562004-08-04 18:46:34 +0000534 - filename: The name of the file that this DocTest was extracted
535 from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000536
Tim Peters8485b562004-08-04 18:46:34 +0000537 - lineno: The line number within filename where this DocTest
538 begins. This line number is zero-based, with respect to the
539 beginning of the file.
540 """
541 def __init__(self, docstring, globs, name, filename, lineno):
542 """
543 Create a new DocTest, by extracting examples from `docstring`.
544 The DocTest's globals are initialized with a copy of `globs`.
545 """
546 # Store a copy of the globals
547 self.globs = globs.copy()
548 # Store identifying information
549 self.name = name
550 self.filename = filename
551 self.lineno = lineno
552 # Parse the docstring.
Tim Peters19397e52004-08-06 22:02:59 +0000553 self.docstring = docstring
Edward Loper78b58f32004-08-09 02:56:02 +0000554 self.examples = Parser(name, docstring).get_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'''
Tim Petersd40a92b2004-08-09 03:28:45 +0000593 # 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('^[ ]*(#.*)?$').match
Edward Loper7c748462004-08-09 02:06:06 +0000605
606 def get_examples(self):
607 """
Edward Loper78b58f32004-08-09 02:56:02 +0000608 Extract all doctest examples, from the string, and return them
609 as a list of `Example` objects. Line numbers are 0-based,
610 because it's most common in doctests that nothing interesting
611 appears on the same line as opening triple-quote, and so the
612 first interesting line is called \"line 1\" then.
Edward Loper7c748462004-08-09 02:06:06 +0000613
614 >>> text = '''
615 ... >>> x, y = 2, 3 # no output expected
616 ... >>> if 1:
617 ... ... print x
618 ... ... print y
619 ... 2
620 ... 3
621 ...
622 ... Some text.
623 ... >>> x+y
624 ... 5
625 ... '''
626 >>> for x in Parser('<string>', text).get_examples():
Edward Loper78b58f32004-08-09 02:56:02 +0000627 ... print (x.source, x.want, x.lineno)
Edward Loper7c748462004-08-09 02:06:06 +0000628 ('x, y = 2, 3 # no output expected', '', 1)
629 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
630 ('x+y', '5\\n', 9)
631 """
632 examples = []
633 charno, lineno = 0, 0
634 # Find all doctest examples in the string:
635 for m in self._EXAMPLE_RE.finditer(self.string):
636 # Update lineno (lines before this example)
637 lineno += self.string.count('\n', charno, m.start())
638
639 # Extract source/want from the regexp match.
640 (source, want) = self._parse_example(m, lineno)
Tim Petersd40a92b2004-08-09 03:28:45 +0000641 if self._IS_BLANK_OR_COMMENT(source):
Edward Loper7c748462004-08-09 02:06:06 +0000642 continue
Edward Loper78b58f32004-08-09 02:56:02 +0000643 examples.append( Example(source, want, lineno) )
Edward Loper7c748462004-08-09 02:06:06 +0000644
645 # Update lineno (lines inside this example)
646 lineno += self.string.count('\n', m.start(), m.end())
647 # Update charno.
648 charno = m.end()
649 return examples
650
651 def get_program(self):
652 """
653 Return an executable program from the string, as a string.
654
655 The format of this isn't rigidly defined. In general, doctest
656 examples become the executable statements in the result, and
657 their expected outputs become comments, preceded by an \"#Expected:\"
658 comment. Everything else (text, comments, everything not part of
659 a doctest test) is also placed in comments.
660
661 >>> text = '''
662 ... >>> x, y = 2, 3 # no output expected
663 ... >>> if 1:
664 ... ... print x
665 ... ... print y
666 ... 2
667 ... 3
668 ...
669 ... Some text.
670 ... >>> x+y
671 ... 5
672 ... '''
673 >>> print Parser('<string>', text).get_program()
674 x, y = 2, 3 # no output expected
675 if 1:
676 print x
677 print y
678 # Expected:
679 # 2
680 # 3
681 #
682 # Some text.
683 x+y
684 # Expected:
685 # 5
686 """
687 output = []
688 charnum, lineno = 0, 0
689 # Find all doctest examples in the string:
690 for m in self._EXAMPLE_RE.finditer(self.string):
691 # Add any text before this example, as a comment.
692 if m.start() > charnum:
693 lines = self.string[charnum:m.start()-1].split('\n')
694 output.extend([self._comment_line(l) for l in lines])
695 lineno += len(lines)
696
697 # Extract source/want from the regexp match.
698 (source, want) = self._parse_example(m, lineno, False)
699 # Display the source
700 output.append(source)
701 # Display the expected output, if any
702 if want:
703 output.append('# Expected:')
704 output.extend(['# '+l for l in want.split('\n')])
705
706 # Update the line number & char number.
707 lineno += self.string.count('\n', m.start(), m.end())
708 charnum = m.end()
709 # Add any remaining text, as comments.
710 output.extend([self._comment_line(l)
711 for l in self.string[charnum:].split('\n')])
712 # Trim junk on both ends.
713 while output and output[-1] == '#':
714 output.pop()
715 while output and output[0] == '#':
716 output.pop(0)
717 # Combine the output, and return it.
718 return '\n'.join(output)
719
720 def _parse_example(self, m, lineno, add_newlines=True):
721 # Get the example's indentation level.
722 indent = len(m.group('indent'))
723
724 # Divide source into lines; check that they're properly
725 # indented; and then strip their indentation & prompts.
726 source_lines = m.group('source').split('\n')
727 self._check_prompt_blank(source_lines, indent, lineno)
728 self._check_prefix(source_lines[1:], ' '*indent+'.', lineno)
729 source = '\n'.join([sl[indent+4:] for sl in source_lines])
730 if len(source_lines) > 1 and add_newlines:
731 source += '\n'
732
733 # Divide want into lines; check that it's properly
734 # indented; and then strip the indentation.
735 want_lines = m.group('want').rstrip().split('\n')
736 self._check_prefix(want_lines, ' '*indent,
737 lineno+len(source_lines))
738 want = '\n'.join([wl[indent:] for wl in want_lines])
739 if len(want) > 0 and add_newlines:
740 want += '\n'
741
742 return source, want
743
744 def _comment_line(self, line):
745 line = line.rstrip()
746 if line: return '# '+line
747 else: return '#'
748
749 def _check_prompt_blank(self, lines, indent, lineno):
750 for i, line in enumerate(lines):
751 if len(line) >= indent+4 and line[indent+3] != ' ':
752 raise ValueError('line %r of the docstring for %s '
753 'lacks blank after %s: %r' %
754 (lineno+i+1, self.name,
755 line[indent:indent+3], line))
756
757 def _check_prefix(self, lines, prefix, lineno):
758 for i, line in enumerate(lines):
759 if line and not line.startswith(prefix):
760 raise ValueError('line %r of the docstring for %s has '
761 'inconsistent leading whitespace: %r' %
762 (lineno+i+1, self.name, line))
763
764
765######################################################################
766## 4. DocTest Finder
Tim Peters8485b562004-08-04 18:46:34 +0000767######################################################################
768
769class DocTestFinder:
770 """
771 A class used to extract the DocTests that are relevant to a given
772 object, from its docstring and the docstrings of its contained
773 objects. Doctests can currently be extracted from the following
774 object types: modules, functions, classes, methods, staticmethods,
775 classmethods, and properties.
Tim Peters8485b562004-08-04 18:46:34 +0000776 """
777
Tim Peters19397e52004-08-06 22:02:59 +0000778 def __init__(self, verbose=False, doctest_factory=DocTest,
Tim Petersf727c6c2004-08-08 01:48:59 +0000779 recurse=True, _namefilter=None):
Tim Peters8485b562004-08-04 18:46:34 +0000780 """
781 Create a new doctest finder.
782
Tim Peters19397e52004-08-06 22:02:59 +0000783 The optional argument `doctest_factory` specifies a class or
784 function that should be used to create new DocTest objects (or
Tim Peters161c9632004-08-08 03:38:33 +0000785 objects that implement the same interface as DocTest). The
Tim Peters19397e52004-08-06 22:02:59 +0000786 signature for this factory function should match the signature
787 of the DocTest constructor.
788
Tim Peters8485b562004-08-04 18:46:34 +0000789 If the optional argument `recurse` is false, then `find` will
790 only examine the given object, and not any contained objects.
791 """
Tim Peters19397e52004-08-06 22:02:59 +0000792 self._doctest_factory = doctest_factory
Tim Peters8485b562004-08-04 18:46:34 +0000793 self._verbose = verbose
Tim Peters8485b562004-08-04 18:46:34 +0000794 self._recurse = recurse
Tim Petersf727c6c2004-08-08 01:48:59 +0000795 # _namefilter is undocumented, and exists only for temporary backward-
796 # compatibility support of testmod's deprecated isprivate mess.
797 self._namefilter = _namefilter
Tim Peters8485b562004-08-04 18:46:34 +0000798
799 def find(self, obj, name=None, module=None, globs=None,
Tim Petersf3f57472004-08-08 06:11:48 +0000800 extraglobs=None):
Tim Peters8485b562004-08-04 18:46:34 +0000801 """
802 Return a list of the DocTests that are defined by the given
803 object's docstring, or by any of its contained objects'
804 docstrings.
805
806 The optional parameter `module` is the module that contains
Tim Petersf3f57472004-08-08 06:11:48 +0000807 the given object. If the module is not specified or is None, then
808 the test finder will attempt to automatically determine the
Tim Peters8485b562004-08-04 18:46:34 +0000809 correct module. The object's module is used:
810
811 - As a default namespace, if `globs` is not specified.
812 - To prevent the DocTestFinder from extracting DocTests
Tim Petersf3f57472004-08-08 06:11:48 +0000813 from objects that are imported from other modules.
Tim Peters8485b562004-08-04 18:46:34 +0000814 - To find the name of the file containing the object.
815 - To help find the line number of the object within its
816 file.
817
Tim Petersf3f57472004-08-08 06:11:48 +0000818 Contained objects whose module does not match `module` are ignored.
819
820 If `module` is False, no attempt to find the module will be made.
821 This is obscure, of use mostly in tests: if `module` is False, or
822 is None but cannot be found automatically, then all objects are
823 considered to belong to the (non-existent) module, so all contained
824 objects will (recursively) be searched for doctests.
825
Tim Peters8485b562004-08-04 18:46:34 +0000826 The globals for each DocTest is formed by combining `globs`
827 and `extraglobs` (bindings in `extraglobs` override bindings
828 in `globs`). A new copy of the globals dictionary is created
829 for each DocTest. If `globs` is not specified, then it
830 defaults to the module's `__dict__`, if specified, or {}
831 otherwise. If `extraglobs` is not specified, then it defaults
832 to {}.
833
Tim Peters8485b562004-08-04 18:46:34 +0000834 """
835 # If name was not specified, then extract it from the object.
836 if name is None:
837 name = getattr(obj, '__name__', None)
838 if name is None:
839 raise ValueError("DocTestFinder.find: name must be given "
840 "when obj.__name__ doesn't exist: %r" %
841 (type(obj),))
842
843 # Find the module that contains the given object (if obj is
844 # a module, then module=obj.). Note: this may fail, in which
845 # case module will be None.
Tim Petersf3f57472004-08-08 06:11:48 +0000846 if module is False:
847 module = None
848 elif module is None:
Tim Peters8485b562004-08-04 18:46:34 +0000849 module = inspect.getmodule(obj)
850
851 # Read the module's source code. This is used by
852 # DocTestFinder._find_lineno to find the line number for a
853 # given object's docstring.
854 try:
855 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
856 source_lines = linecache.getlines(file)
857 if not source_lines:
858 source_lines = None
859 except TypeError:
860 source_lines = None
861
862 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000863 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000864 if module is None:
865 globs = {}
866 else:
867 globs = module.__dict__.copy()
868 else:
869 globs = globs.copy()
870 if extraglobs is not None:
871 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000872
Tim Peters8485b562004-08-04 18:46:34 +0000873 # Recursively expore `obj`, extracting DocTests.
874 tests = []
Tim Petersf3f57472004-08-08 06:11:48 +0000875 self._find(tests, obj, name, module, source_lines, globs, {})
Tim Peters8485b562004-08-04 18:46:34 +0000876 return tests
877
878 def _filter(self, obj, prefix, base):
879 """
880 Return true if the given object should not be examined.
881 """
Tim Petersf727c6c2004-08-08 01:48:59 +0000882 return (self._namefilter is not None and
883 self._namefilter(prefix, base))
Tim Peters8485b562004-08-04 18:46:34 +0000884
885 def _from_module(self, module, object):
886 """
887 Return true if the given object is defined in the given
888 module.
889 """
890 if module is None:
891 return True
892 elif inspect.isfunction(object):
893 return module.__dict__ is object.func_globals
894 elif inspect.isclass(object):
895 return module.__name__ == object.__module__
896 elif inspect.getmodule(object) is not None:
897 return module is inspect.getmodule(object)
898 elif hasattr(object, '__module__'):
899 return module.__name__ == object.__module__
900 elif isinstance(object, property):
901 return True # [XX] no way not be sure.
902 else:
903 raise ValueError("object must be a class or function")
904
Tim Petersf3f57472004-08-08 06:11:48 +0000905 def _find(self, tests, obj, name, module, source_lines, globs, seen):
Tim Peters8485b562004-08-04 18:46:34 +0000906 """
907 Find tests for the given object and any contained objects, and
908 add them to `tests`.
909 """
910 if self._verbose:
911 print 'Finding tests in %s' % name
912
913 # If we've already processed this object, then ignore it.
914 if id(obj) in seen:
915 return
916 seen[id(obj)] = 1
917
918 # Find a test for this object, and add it to the list of tests.
919 test = self._get_test(obj, name, module, globs, source_lines)
920 if test is not None:
921 tests.append(test)
922
923 # Look for tests in a module's contained objects.
924 if inspect.ismodule(obj) and self._recurse:
925 for valname, val in obj.__dict__.items():
926 # Check if this contained object should be ignored.
927 if self._filter(val, name, valname):
928 continue
929 valname = '%s.%s' % (name, valname)
930 # Recurse to functions & classes.
931 if ((inspect.isfunction(val) or inspect.isclass(val)) and
Tim Petersf3f57472004-08-08 06:11:48 +0000932 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000933 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000934 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000935
936 # Look for tests in a module's __test__ dictionary.
937 if inspect.ismodule(obj) and self._recurse:
938 for valname, val in getattr(obj, '__test__', {}).items():
939 if not isinstance(valname, basestring):
940 raise ValueError("DocTestFinder.find: __test__ keys "
941 "must be strings: %r" %
942 (type(valname),))
943 if not (inspect.isfunction(val) or inspect.isclass(val) or
944 inspect.ismethod(val) or inspect.ismodule(val) or
945 isinstance(val, basestring)):
946 raise ValueError("DocTestFinder.find: __test__ values "
947 "must be strings, functions, methods, "
948 "classes, or modules: %r" %
949 (type(val),))
950 valname = '%s.%s' % (name, valname)
951 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000952 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000953
954 # Look for tests in a class's contained objects.
955 if inspect.isclass(obj) and self._recurse:
956 for valname, val in obj.__dict__.items():
957 # Check if this contained object should be ignored.
958 if self._filter(val, name, valname):
959 continue
960 # Special handling for staticmethod/classmethod.
961 if isinstance(val, staticmethod):
962 val = getattr(obj, valname)
963 if isinstance(val, classmethod):
964 val = getattr(obj, valname).im_func
965
966 # Recurse to methods, properties, and nested classes.
967 if ((inspect.isfunction(val) or inspect.isclass(val) or
Tim Petersf3f57472004-08-08 06:11:48 +0000968 isinstance(val, property)) and
969 self._from_module(module, val)):
Tim Peters8485b562004-08-04 18:46:34 +0000970 valname = '%s.%s' % (name, valname)
971 self._find(tests, val, valname, module, source_lines,
Tim Petersf3f57472004-08-08 06:11:48 +0000972 globs, seen)
Tim Peters8485b562004-08-04 18:46:34 +0000973
974 def _get_test(self, obj, name, module, globs, source_lines):
975 """
976 Return a DocTest for the given object, if it defines a docstring;
977 otherwise, return None.
978 """
979 # Extract the object's docstring. If it doesn't have one,
980 # then return None (no test for this object).
981 if isinstance(obj, basestring):
982 docstring = obj
983 else:
984 try:
985 if obj.__doc__ is None:
986 return None
987 docstring = str(obj.__doc__)
988 except (TypeError, AttributeError):
989 return None
990
991 # Don't bother if the docstring is empty.
992 if not docstring:
993 return None
994
995 # Find the docstring's location in the file.
996 lineno = self._find_lineno(obj, source_lines)
997
998 # Return a DocTest for this object.
999 if module is None:
1000 filename = None
1001 else:
1002 filename = getattr(module, '__file__', module.__name__)
Tim Peters19397e52004-08-06 22:02:59 +00001003 return self._doctest_factory(docstring, globs, name, filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001004
1005 def _find_lineno(self, obj, source_lines):
1006 """
1007 Return a line number of the given object's docstring. Note:
1008 this method assumes that the object has a docstring.
1009 """
1010 lineno = None
1011
1012 # Find the line number for modules.
1013 if inspect.ismodule(obj):
1014 lineno = 0
1015
1016 # Find the line number for classes.
1017 # Note: this could be fooled if a class is defined multiple
1018 # times in a single file.
1019 if inspect.isclass(obj):
1020 if source_lines is None:
1021 return None
1022 pat = re.compile(r'^\s*class\s*%s\b' %
1023 getattr(obj, '__name__', '-'))
1024 for i, line in enumerate(source_lines):
1025 if pat.match(line):
1026 lineno = i
1027 break
1028
1029 # Find the line number for functions & methods.
1030 if inspect.ismethod(obj): obj = obj.im_func
1031 if inspect.isfunction(obj): obj = obj.func_code
1032 if inspect.istraceback(obj): obj = obj.tb_frame
1033 if inspect.isframe(obj): obj = obj.f_code
1034 if inspect.iscode(obj):
1035 lineno = getattr(obj, 'co_firstlineno', None)-1
1036
1037 # Find the line number where the docstring starts. Assume
1038 # that it's the first line that begins with a quote mark.
1039 # Note: this could be fooled by a multiline function
1040 # signature, where a continuation line begins with a quote
1041 # mark.
1042 if lineno is not None:
1043 if source_lines is None:
1044 return lineno+1
1045 pat = re.compile('(^|.*:)\s*\w*("|\')')
1046 for lineno in range(lineno, len(source_lines)):
1047 if pat.match(source_lines[lineno]):
1048 return lineno
1049
1050 # We couldn't find the line number.
1051 return None
1052
1053######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001054## 5. DocTest Runner
Tim Peters8485b562004-08-04 18:46:34 +00001055######################################################################
1056
Tim Peters8485b562004-08-04 18:46:34 +00001057class DocTestRunner:
1058 """
1059 A class used to run DocTest test cases, and accumulate statistics.
1060 The `run` method is used to process a single DocTest case. It
1061 returns a tuple `(f, t)`, where `t` is the number of test cases
1062 tried, and `f` is the number of test cases that failed.
1063
1064 >>> tests = DocTestFinder().find(_TestClass)
1065 >>> runner = DocTestRunner(verbose=False)
1066 >>> for test in tests:
1067 ... print runner.run(test)
1068 (0, 2)
1069 (0, 1)
1070 (0, 2)
1071 (0, 2)
1072
1073 The `summarize` method prints a summary of all the test cases that
1074 have been run by the runner, and returns an aggregated `(f, t)`
1075 tuple:
1076
1077 >>> runner.summarize(verbose=1)
1078 4 items passed all tests:
1079 2 tests in _TestClass
1080 2 tests in _TestClass.__init__
1081 2 tests in _TestClass.get
1082 1 tests in _TestClass.square
1083 7 tests in 4 items.
1084 7 passed and 0 failed.
1085 Test passed.
1086 (0, 7)
1087
1088 The aggregated number of tried examples and failed examples is
1089 also available via the `tries` and `failures` attributes:
1090
1091 >>> runner.tries
1092 7
1093 >>> runner.failures
1094 0
1095
1096 The comparison between expected outputs and actual outputs is done
Edward Loper34fcb142004-08-09 02:45:41 +00001097 by an `OutputChecker`. This comparison may be customized with a
1098 number of option flags; see the documentation for `testmod` for
1099 more information. If the option flags are insufficient, then the
1100 comparison may also be customized by passing a subclass of
1101 `OutputChecker` to the constructor.
Tim Peters8485b562004-08-04 18:46:34 +00001102
1103 The test runner's display output can be controlled in two ways.
1104 First, an output function (`out) can be passed to
1105 `TestRunner.run`; this function will be called with strings that
1106 should be displayed. It defaults to `sys.stdout.write`. If
1107 capturing the output is not sufficient, then the display output
1108 can be also customized by subclassing DocTestRunner, and
1109 overriding the methods `report_start`, `report_success`,
1110 `report_unexpected_exception`, and `report_failure`.
1111 """
1112 # This divider string is used to separate failure messages, and to
1113 # separate sections of the summary.
1114 DIVIDER = "*" * 70
1115
Edward Loper34fcb142004-08-09 02:45:41 +00001116 def __init__(self, checker=None, verbose=None, optionflags=0):
Tim Peters8485b562004-08-04 18:46:34 +00001117 """
1118 Create a new test runner.
1119
Edward Loper34fcb142004-08-09 02:45:41 +00001120 Optional keyword arg `checker` is the `OutputChecker` that
1121 should be used to compare the expected outputs and actual
1122 outputs of doctest examples.
1123
Tim Peters8485b562004-08-04 18:46:34 +00001124 Optional keyword arg 'verbose' prints lots of stuff if true,
1125 only failures if false; by default, it's true iff '-v' is in
1126 sys.argv.
1127
1128 Optional argument `optionflags` can be used to control how the
1129 test runner compares expected output to actual output, and how
1130 it displays failures. See the documentation for `testmod` for
1131 more information.
1132 """
Edward Loper34fcb142004-08-09 02:45:41 +00001133 self._checker = checker or OutputChecker()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001134 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001135 verbose = '-v' in sys.argv
1136 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001137 self.optionflags = optionflags
1138
Tim Peters8485b562004-08-04 18:46:34 +00001139 # Keep track of the examples we've run.
1140 self.tries = 0
1141 self.failures = 0
1142 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001143
Tim Peters8485b562004-08-04 18:46:34 +00001144 # Create a fake output target for capturing doctest output.
1145 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001146
Tim Peters8485b562004-08-04 18:46:34 +00001147 #/////////////////////////////////////////////////////////////////
Tim Peters8485b562004-08-04 18:46:34 +00001148 # Reporting methods
1149 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001150
Tim Peters8485b562004-08-04 18:46:34 +00001151 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001152 """
Tim Peters8485b562004-08-04 18:46:34 +00001153 Report that the test runner is about to process the given
1154 example. (Only displays a message if verbose=True)
1155 """
1156 if self._verbose:
1157 out(_tag_msg("Trying", example.source) +
1158 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001159
Tim Peters8485b562004-08-04 18:46:34 +00001160 def report_success(self, out, test, example, got):
1161 """
1162 Report that the given example ran successfully. (Only
1163 displays a message if verbose=True)
1164 """
1165 if self._verbose:
1166 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001167
Tim Peters8485b562004-08-04 18:46:34 +00001168 def report_failure(self, out, test, example, got):
1169 """
1170 Report that the given example failed.
1171 """
1172 # Print an error message.
1173 out(self.__failure_header(test, example) +
Edward Loper34fcb142004-08-09 02:45:41 +00001174 self._checker.output_difference(example.want, got,
1175 self.optionflags))
Tim Peters7402f792001-10-02 03:53:41 +00001176
Tim Peters8485b562004-08-04 18:46:34 +00001177 def report_unexpected_exception(self, out, test, example, exc_info):
1178 """
1179 Report that the given example raised an unexpected exception.
1180 """
1181 # Get a traceback message.
1182 excout = StringIO()
1183 exc_type, exc_val, exc_tb = exc_info
1184 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
1185 exception_tb = excout.getvalue()
1186 # Print an error message.
1187 out(self.__failure_header(test, example) +
1188 _tag_msg("Exception raised", exception_tb))
Tim Peters7402f792001-10-02 03:53:41 +00001189
Tim Peters8485b562004-08-04 18:46:34 +00001190 def __failure_header(self, test, example):
1191 s = (self.DIVIDER + "\n" +
1192 _tag_msg("Failure in example", example.source))
1193 if test.filename is None:
1194 # [XX] I'm not putting +1 here, to give the same output
1195 # as the old version. But I think it *should* go here.
1196 return s + ("from line #%s of %s\n" %
1197 (example.lineno, test.name))
1198 elif test.lineno is None:
1199 return s + ("from line #%s of %s in %s\n" %
1200 (example.lineno+1, test.name, test.filename))
1201 else:
1202 lineno = test.lineno+example.lineno+1
1203 return s + ("from line #%s of %s (%s)\n" %
1204 (lineno, test.filename, test.name))
Tim Peters7402f792001-10-02 03:53:41 +00001205
Tim Peters8485b562004-08-04 18:46:34 +00001206 #/////////////////////////////////////////////////////////////////
1207 # DocTest Running
1208 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001209
Tim Peters8485b562004-08-04 18:46:34 +00001210 # A regular expression for handling `want` strings that contain
1211 # expected exceptions. It divides `want` into two pieces: the
1212 # pre-exception output (`out`) and the exception message (`exc`),
1213 # as generated by traceback.format_exception_only(). (I assume
1214 # that the exception_only message is the first non-indented line
1215 # starting with word characters after the "Traceback ...".)
1216 _EXCEPTION_RE = re.compile(('^(?P<out>.*)'
1217 '^(?P<hdr>Traceback \((?:%s|%s)\):)\s*$.*?'
1218 '^(?P<exc>\w+.*)') %
1219 ('most recent call last', 'innermost last'),
1220 re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001221
Tim Peters8485b562004-08-04 18:46:34 +00001222 _OPTION_DIRECTIVE_RE = re.compile('\s*doctest:\s*(?P<flags>[^#\n]*)')
Tim Peters7402f792001-10-02 03:53:41 +00001223
Tim Peters8485b562004-08-04 18:46:34 +00001224 def __handle_directive(self, example):
1225 """
1226 Check if the given example is actually a directive to doctest
1227 (to turn an optionflag on or off); and if it is, then handle
1228 the directive.
Tim Peters7402f792001-10-02 03:53:41 +00001229
Tim Peters8485b562004-08-04 18:46:34 +00001230 Return true iff the example is actually a directive (and so
1231 should not be executed).
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001232
Tim Peters8a7d2d52001-01-16 07:10:57 +00001233 """
Tim Peters8485b562004-08-04 18:46:34 +00001234 m = self._OPTION_DIRECTIVE_RE.match(example.source)
1235 if m is None:
1236 return False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001237
Tim Peters8485b562004-08-04 18:46:34 +00001238 for flag in m.group('flags').upper().split():
1239 if (flag[:1] not in '+-' or
1240 flag[1:] not in OPTIONFLAGS_BY_NAME):
1241 raise ValueError('Bad doctest option directive: '+flag)
1242 if flag[0] == '+':
1243 self.optionflags |= OPTIONFLAGS_BY_NAME[flag[1:]]
1244 else:
1245 self.optionflags &= ~OPTIONFLAGS_BY_NAME[flag[1:]]
1246 return True
Tim Peters8a7d2d52001-01-16 07:10:57 +00001247
Tim Peters8485b562004-08-04 18:46:34 +00001248 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001249 """
Tim Peters8485b562004-08-04 18:46:34 +00001250 Run the examples in `test`. Write the outcome of each example
1251 with one of the `DocTestRunner.report_*` methods, using the
1252 writer function `out`. `compileflags` is the set of compiler
1253 flags that should be used to execute examples. Return a tuple
1254 `(f, t)`, where `t` is the number of examples tried, and `f`
1255 is the number of examples that failed. The examples are run
1256 in the namespace `test.globs`.
1257 """
1258 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001259 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001260
1261 # Save the option flags (since option directives can be used
1262 # to modify them).
1263 original_optionflags = self.optionflags
1264
1265 # Process each example.
1266 for example in test.examples:
1267 # Check if it's an option directive. If it is, then handle
1268 # it, and go on to the next example.
1269 if self.__handle_directive(example):
1270 continue
1271
1272 # Record that we started this example.
1273 tries += 1
1274 self.report_start(out, test, example)
1275
1276 # Run the example in the given context (globs), and record
1277 # any exception that gets raised. (But don't intercept
1278 # keyboard interrupts.)
1279 try:
1280 # If the example is a compound statement on one line,
1281 # like "if 1: print 2", then compile() requires a
1282 # trailing newline. Rather than analyze that, always
1283 # append one (it never hurts).
1284 exec compile(example.source + '\n', "<string>", "single",
1285 compileflags, 1) in test.globs
1286 exception = None
1287 except KeyboardInterrupt:
1288 raise
1289 except:
1290 exception = sys.exc_info()
1291
1292 # Extract the example's actual output from fakeout, and
1293 # write it to `got`. Add a terminating newline if it
1294 # doesn't have already one.
1295 got = self._fakeout.getvalue()
1296 self._fakeout.truncate(0)
1297
1298 # If the example executed without raising any exceptions,
1299 # then verify its output and report its outcome.
1300 if exception is None:
Edward Loper34fcb142004-08-09 02:45:41 +00001301 if self._checker.check_output(example.want, got,
1302 self.optionflags):
Tim Peters8485b562004-08-04 18:46:34 +00001303 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001304 else:
Tim Peters8485b562004-08-04 18:46:34 +00001305 self.report_failure(out, test, example, got)
1306 failures += 1
1307
1308 # If the example raised an exception, then check if it was
1309 # expected.
1310 else:
1311 exc_info = sys.exc_info()
1312 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1313
1314 # Search the `want` string for an exception. If we don't
1315 # find one, then report an unexpected exception.
1316 m = self._EXCEPTION_RE.match(example.want)
1317 if m is None:
1318 self.report_unexpected_exception(out, test, example,
1319 exc_info)
1320 failures += 1
1321 else:
1322 exc_hdr = m.group('hdr')+'\n' # Exception header
1323 # The test passes iff the pre-exception output and
1324 # the exception description match the values given
1325 # in `want`.
Edward Loper34fcb142004-08-09 02:45:41 +00001326 if (self._checker.check_output(m.group('out'), got,
1327 self.optionflags) and
1328 self._checker.check_output(m.group('exc'), exc_msg,
1329 self.optionflags)):
Tim Peters8485b562004-08-04 18:46:34 +00001330 # Is +exc_msg the right thing here??
1331 self.report_success(out, test, example,
1332 got+exc_hdr+exc_msg)
1333 else:
1334 self.report_failure(out, test, example,
1335 got+exc_hdr+exc_msg)
1336 failures += 1
1337
1338 # Restore the option flags (in case they were modified)
1339 self.optionflags = original_optionflags
1340
1341 # Record and return the number of failures and tries.
1342 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001343 return failures, tries
1344
Tim Peters8485b562004-08-04 18:46:34 +00001345 def __record_outcome(self, test, f, t):
1346 """
1347 Record the fact that the given DocTest (`test`) generated `f`
1348 failures out of `t` tried examples.
1349 """
1350 f2, t2 = self._name2ft.get(test.name, (0,0))
1351 self._name2ft[test.name] = (f+f2, t+t2)
1352 self.failures += f
1353 self.tries += t
1354
1355 def run(self, test, compileflags=None, out=None, clear_globs=True):
1356 """
1357 Run the examples in `test`, and display the results using the
1358 writer function `out`.
1359
1360 The examples are run in the namespace `test.globs`. If
1361 `clear_globs` is true (the default), then this namespace will
1362 be cleared after the test runs, to help with garbage
1363 collection. If you would like to examine the namespace after
1364 the test completes, then use `clear_globs=False`.
1365
1366 `compileflags` gives the set of flags that should be used by
1367 the Python compiler when running the examples. If not
1368 specified, then it will default to the set of future-import
1369 flags that apply to `globs`.
1370
1371 The output of each example is checked using
1372 `DocTestRunner.check_output`, and the results are formatted by
1373 the `DocTestRunner.report_*` methods.
1374 """
1375 if compileflags is None:
1376 compileflags = _extract_future_flags(test.globs)
1377 if out is None:
1378 out = sys.stdout.write
1379 saveout = sys.stdout
1380
1381 try:
1382 sys.stdout = self._fakeout
1383 return self.__run(test, compileflags, out)
1384 finally:
1385 sys.stdout = saveout
Tim Peters8485b562004-08-04 18:46:34 +00001386 if clear_globs:
1387 test.globs.clear()
1388
1389 #/////////////////////////////////////////////////////////////////
1390 # Summarization
1391 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001392 def summarize(self, verbose=None):
1393 """
Tim Peters8485b562004-08-04 18:46:34 +00001394 Print a summary of all the test cases that have been run by
1395 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1396 the total number of failed examples, and `t` is the total
1397 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001398
Tim Peters8485b562004-08-04 18:46:34 +00001399 The optional `verbose` argument controls how detailed the
1400 summary is. If the verbosity is not specified, then the
1401 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001402 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001403 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001404 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001405 notests = []
1406 passed = []
1407 failed = []
1408 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001409 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001410 name, (f, t) = x
1411 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001412 totalt += t
1413 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001414 if t == 0:
1415 notests.append(name)
1416 elif f == 0:
1417 passed.append( (name, t) )
1418 else:
1419 failed.append(x)
1420 if verbose:
1421 if notests:
1422 print len(notests), "items had no tests:"
1423 notests.sort()
1424 for thing in notests:
1425 print " ", thing
1426 if passed:
1427 print len(passed), "items passed all tests:"
1428 passed.sort()
1429 for thing, count in passed:
1430 print " %3d tests in %s" % (count, thing)
1431 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001432 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001433 print len(failed), "items had failures:"
1434 failed.sort()
1435 for thing, (f, t) in failed:
1436 print " %3d of %3d in %s" % (f, t, thing)
1437 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001438 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001439 print totalt - totalf, "passed and", totalf, "failed."
1440 if totalf:
1441 print "***Test Failed***", totalf, "failures."
1442 elif verbose:
1443 print "Test passed."
1444 return totalf, totalt
1445
Edward Loper34fcb142004-08-09 02:45:41 +00001446class OutputChecker:
1447 """
1448 A class used to check the whether the actual output from a doctest
1449 example matches the expected output. `OutputChecker` defines two
1450 methods: `check_output`, which compares a given pair of outputs,
1451 and returns true if they match; and `output_difference`, which
1452 returns a string describing the differences between two outputs.
1453 """
1454 def check_output(self, want, got, optionflags):
1455 """
1456 Return True iff the actual output (`got`) matches the expected
1457 output (`want`). These strings are always considered to match
1458 if they are identical; but depending on what option flags the
1459 test runner is using, several non-exact match types are also
1460 possible. See the documentation for `TestRunner` for more
1461 information about option flags.
1462 """
1463 # Handle the common case first, for efficiency:
1464 # if they're string-identical, always return true.
1465 if got == want:
1466 return True
1467
1468 # The values True and False replaced 1 and 0 as the return
1469 # value for boolean comparisons in Python 2.3.
1470 if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
1471 if (got,want) == ("True\n", "1\n"):
1472 return True
1473 if (got,want) == ("False\n", "0\n"):
1474 return True
1475
1476 # <BLANKLINE> can be used as a special sequence to signify a
1477 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1478 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1479 # Replace <BLANKLINE> in want with a blank line.
1480 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1481 '', want)
1482 # If a line in got contains only spaces, then remove the
1483 # spaces.
1484 got = re.sub('(?m)^\s*?$', '', got)
1485 if got == want:
1486 return True
1487
1488 # This flag causes doctest to ignore any differences in the
1489 # contents of whitespace strings. Note that this can be used
1490 # in conjunction with the ELLISPIS flag.
1491 if (optionflags & NORMALIZE_WHITESPACE):
1492 got = ' '.join(got.split())
1493 want = ' '.join(want.split())
1494 if got == want:
1495 return True
1496
1497 # The ELLIPSIS flag says to let the sequence "..." in `want`
1498 # match any substring in `got`. We implement this by
1499 # transforming `want` into a regular expression.
1500 if (optionflags & ELLIPSIS):
1501 # Escape any special regexp characters
1502 want_re = re.escape(want)
1503 # Replace ellipsis markers ('...') with .*
1504 want_re = want_re.replace(re.escape(ELLIPSIS_MARKER), '.*')
1505 # Require that it matches the entire string; and set the
1506 # re.DOTALL flag (with '(?s)').
1507 want_re = '(?s)^%s$' % want_re
1508 # Check if the `want_re` regexp matches got.
1509 if re.match(want_re, got):
1510 return True
1511
1512 # We didn't find any match; return false.
1513 return False
1514
1515 def output_difference(self, want, got, optionflags):
1516 """
1517 Return a string describing the differences between the
1518 expected output (`want`) and the actual output (`got`).
1519 """
1520 # If <BLANKLINE>s are being used, then replace <BLANKLINE>
1521 # with blank lines in the expected output string.
1522 if not (optionflags & DONT_ACCEPT_BLANKLINE):
1523 want = re.sub('(?m)^%s$' % re.escape(BLANKLINE_MARKER), '', want)
1524
1525 # Check if we should use diff. Don't use diff if the actual
1526 # or expected outputs are too short, or if the expected output
1527 # contains an ellipsis marker.
1528 if ((optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and
1529 want.count('\n') > 2 and got.count('\n') > 2 and
1530 not (optionflags & ELLIPSIS and '...' in want)):
1531 # Split want & got into lines.
1532 want_lines = [l+'\n' for l in want.split('\n')]
1533 got_lines = [l+'\n' for l in got.split('\n')]
1534 # Use difflib to find their differences.
1535 if optionflags & UNIFIED_DIFF:
1536 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1537 fromfile='Expected', tofile='Got')
1538 kind = 'unified'
1539 elif optionflags & CONTEXT_DIFF:
1540 diff = difflib.context_diff(want_lines, got_lines, n=2,
1541 fromfile='Expected', tofile='Got')
1542 kind = 'context'
1543 else:
1544 assert 0, 'Bad diff option'
1545 # Remove trailing whitespace on diff output.
1546 diff = [line.rstrip() + '\n' for line in diff]
1547 return _tag_msg("Differences (" + kind + " diff)",
1548 ''.join(diff))
1549
1550 # If we're not using diff, then simply list the expected
1551 # output followed by the actual output.
1552 return (_tag_msg("Expected", want or "Nothing") +
1553 _tag_msg("Got", got))
1554
Tim Peters19397e52004-08-06 22:02:59 +00001555class DocTestFailure(Exception):
1556 """A DocTest example has failed in debugging mode.
1557
1558 The exception instance has variables:
1559
1560 - test: the DocTest object being run
1561
1562 - excample: the Example object that failed
1563
1564 - got: the actual output
1565 """
1566 def __init__(self, test, example, got):
1567 self.test = test
1568 self.example = example
1569 self.got = got
1570
1571 def __str__(self):
1572 return str(self.test)
1573
1574class UnexpectedException(Exception):
1575 """A DocTest example has encountered an unexpected exception
1576
1577 The exception instance has variables:
1578
1579 - test: the DocTest object being run
1580
1581 - excample: the Example object that failed
1582
1583 - exc_info: the exception info
1584 """
1585 def __init__(self, test, example, exc_info):
1586 self.test = test
1587 self.example = example
1588 self.exc_info = exc_info
1589
1590 def __str__(self):
1591 return str(self.test)
Tim Petersd1b78272004-08-07 06:03:09 +00001592
Tim Peters19397e52004-08-06 22:02:59 +00001593class DebugRunner(DocTestRunner):
1594 r"""Run doc tests but raise an exception as soon as there is a failure.
1595
1596 If an unexpected exception occurs, an UnexpectedException is raised.
1597 It contains the test, the example, and the original exception:
1598
1599 >>> runner = DebugRunner(verbose=False)
1600 >>> test = DocTest('>>> raise KeyError\n42', {}, 'foo', 'foo.py', 0)
1601 >>> try:
1602 ... runner.run(test)
1603 ... except UnexpectedException, failure:
1604 ... pass
1605
1606 >>> failure.test is test
1607 True
1608
1609 >>> failure.example.want
1610 '42\n'
1611
1612 >>> exc_info = failure.exc_info
1613 >>> raise exc_info[0], exc_info[1], exc_info[2]
1614 Traceback (most recent call last):
1615 ...
1616 KeyError
1617
1618 We wrap the original exception to give the calling application
1619 access to the test and example information.
1620
1621 If the output doesn't match, then a DocTestFailure is raised:
1622
1623 >>> test = DocTest('''
1624 ... >>> x = 1
1625 ... >>> x
1626 ... 2
1627 ... ''', {}, 'foo', 'foo.py', 0)
1628
1629 >>> try:
1630 ... runner.run(test)
1631 ... except DocTestFailure, failure:
1632 ... pass
1633
1634 DocTestFailure objects provide access to the test:
1635
1636 >>> failure.test is test
1637 True
1638
1639 As well as to the example:
1640
1641 >>> failure.example.want
1642 '2\n'
1643
1644 and the actual output:
1645
1646 >>> failure.got
1647 '1\n'
1648
1649 If a failure or error occurs, the globals are left intact:
1650
1651 >>> del test.globs['__builtins__']
1652 >>> test.globs
1653 {'x': 1}
1654
1655 >>> test = DocTest('''
1656 ... >>> x = 2
1657 ... >>> raise KeyError
1658 ... ''', {}, 'foo', 'foo.py', 0)
1659
1660 >>> runner.run(test)
1661 Traceback (most recent call last):
1662 ...
1663 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
Tim Petersd1b78272004-08-07 06:03:09 +00001664
Tim Peters19397e52004-08-06 22:02:59 +00001665 >>> del test.globs['__builtins__']
1666 >>> test.globs
1667 {'x': 2}
1668
1669 But the globals are cleared if there is no error:
1670
1671 >>> test = DocTest('''
1672 ... >>> x = 2
1673 ... ''', {}, 'foo', 'foo.py', 0)
1674
1675 >>> runner.run(test)
1676 (0, 1)
1677
1678 >>> test.globs
1679 {}
1680
1681 """
1682
1683 def run(self, test, compileflags=None, out=None, clear_globs=True):
1684 r = DocTestRunner.run(self, test, compileflags, out, False)
1685 if clear_globs:
1686 test.globs.clear()
1687 return r
1688
1689 def report_unexpected_exception(self, out, test, example, exc_info):
1690 raise UnexpectedException(test, example, exc_info)
1691
1692 def report_failure(self, out, test, example, got):
1693 raise DocTestFailure(test, example, got)
1694
Tim Peters8485b562004-08-04 18:46:34 +00001695######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001696## 6. Test Functions
Tim Peters8485b562004-08-04 18:46:34 +00001697######################################################################
1698# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001699
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001700def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001701 report=True, optionflags=0, extraglobs=None,
1702 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001703 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001704 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001705
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001706 Test examples in docstrings in functions and classes reachable
1707 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001708 with m.__doc__. Unless isprivate is specified, private names
1709 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001710
1711 Also test examples reachable from dict m.__test__ if it exists and is
1712 not None. m.__dict__ maps names to functions, classes and strings;
1713 function and class docstrings are tested even if the name is private;
1714 strings are tested directly, as if they were docstrings.
1715
1716 Return (#failures, #tests).
1717
1718 See doctest.__doc__ for an overview.
1719
1720 Optional keyword arg "name" gives the name of the module; by default
1721 use m.__name__.
1722
1723 Optional keyword arg "globs" gives a dict to be used as the globals
1724 when executing examples; by default, use m.__dict__. A copy of this
1725 dict is actually used for each docstring, so that each docstring's
1726 examples start with a clean slate.
1727
Tim Peters8485b562004-08-04 18:46:34 +00001728 Optional keyword arg "extraglobs" gives a dictionary that should be
1729 merged into the globals that are used to execute examples. By
1730 default, no extra globals are used. This is new in 2.4.
1731
Tim Peters8a7d2d52001-01-16 07:10:57 +00001732 Optional keyword arg "verbose" prints lots of stuff if true, prints
1733 only failures if false; by default, it's true iff "-v" is in sys.argv.
1734
Tim Peters8a7d2d52001-01-16 07:10:57 +00001735 Optional keyword arg "report" prints a summary at the end when true,
1736 else prints nothing at the end. In verbose mode, the summary is
1737 detailed, else very brief (in fact, empty if all tests passed).
1738
Tim Peters6ebe61f2003-06-27 20:48:05 +00001739 Optional keyword arg "optionflags" or's together module constants,
1740 and defaults to 0. This is new in 2.3. Possible values:
1741
1742 DONT_ACCEPT_TRUE_FOR_1
1743 By default, if an expected output block contains just "1",
1744 an actual output block containing just "True" is considered
1745 to be a match, and similarly for "0" versus "False". When
1746 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1747 is allowed.
1748
Tim Peters8485b562004-08-04 18:46:34 +00001749 DONT_ACCEPT_BLANKLINE
1750 By default, if an expected output block contains a line
1751 containing only the string "<BLANKLINE>", then that line
1752 will match a blank line in the actual output. When
1753 DONT_ACCEPT_BLANKLINE is specified, this substitution is
1754 not allowed.
1755
1756 NORMALIZE_WHITESPACE
1757 When NORMALIZE_WHITESPACE is specified, all sequences of
1758 whitespace are treated as equal. I.e., any sequence of
1759 whitespace within the expected output will match any
1760 sequence of whitespace within the actual output.
1761
1762 ELLIPSIS
1763 When ELLIPSIS is specified, then an ellipsis marker
1764 ("...") in the expected output can match any substring in
1765 the actual output.
1766
1767 UNIFIED_DIFF
1768 When UNIFIED_DIFF is specified, failures that involve
1769 multi-line expected and actual outputs will be displayed
1770 using a unified diff.
1771
1772 CONTEXT_DIFF
1773 When CONTEXT_DIFF is specified, failures that involve
1774 multi-line expected and actual outputs will be displayed
1775 using a context diff.
Tim Peters19397e52004-08-06 22:02:59 +00001776
1777 Optional keyword arg "raise_on_error" raises an exception on the
1778 first unexpected exception or failure. This allows failures to be
1779 post-mortem debugged.
1780
Tim Petersf727c6c2004-08-08 01:48:59 +00001781 Deprecated in Python 2.4:
1782 Optional keyword arg "isprivate" specifies a function used to
1783 determine whether a name is private. The default function is
1784 treat all functions as public. Optionally, "isprivate" can be
1785 set to doctest.is_private to skip over functions marked as private
1786 using the underscore naming convention; see its docs for details.
Tim Peters8485b562004-08-04 18:46:34 +00001787 """
1788
1789 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001790 Advanced tomfoolery: testmod runs methods of a local instance of
1791 class doctest.Tester, then merges the results into (or creates)
1792 global Tester instance doctest.master. Methods of doctest.master
1793 can be called directly too, if you want to do something unusual.
1794 Passing report=0 to testmod is especially useful then, to delay
1795 displaying a summary. Invoke doctest.master.summarize(verbose)
1796 when you're done fiddling.
1797 """
Tim Petersf727c6c2004-08-08 01:48:59 +00001798 if isprivate is not None:
1799 warnings.warn("the isprivate argument is deprecated; "
1800 "examine DocTestFinder.find() lists instead",
1801 DeprecationWarning)
1802
Tim Peters8485b562004-08-04 18:46:34 +00001803 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001804 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001805 # DWA - m will still be None if this wasn't invoked from the command
1806 # line, in which case the following TypeError is about as good an error
1807 # as we should expect
1808 m = sys.modules.get('__main__')
1809
Tim Peters8485b562004-08-04 18:46:34 +00001810 # Check that we were actually given a module.
1811 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001812 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001813
1814 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001815 if name is None:
1816 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001817
1818 # Find, parse, and run all tests in the given module.
Tim Petersf727c6c2004-08-08 01:48:59 +00001819 finder = DocTestFinder(_namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001820
1821 if raise_on_error:
1822 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1823 else:
1824 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1825
Tim Peters8485b562004-08-04 18:46:34 +00001826 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1827 runner.run(test)
1828
Tim Peters8a7d2d52001-01-16 07:10:57 +00001829 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001830 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001831
Tim Peters8485b562004-08-04 18:46:34 +00001832 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001833
Tim Peters8485b562004-08-04 18:46:34 +00001834def run_docstring_examples(f, globs, verbose=False, name="NoName",
1835 compileflags=None, optionflags=0):
1836 """
1837 Test examples in the given object's docstring (`f`), using `globs`
1838 as globals. Optional argument `name` is used in failure messages.
1839 If the optional argument `verbose` is true, then generate output
1840 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001841
Tim Peters8485b562004-08-04 18:46:34 +00001842 `compileflags` gives the set of flags that should be used by the
1843 Python compiler when running the examples. If not specified, then
1844 it will default to the set of future-import flags that apply to
1845 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001846
Tim Peters8485b562004-08-04 18:46:34 +00001847 Optional keyword arg `optionflags` specifies options for the
1848 testing and output. See the documentation for `testmod` for more
1849 information.
1850 """
1851 # Find, parse, and run all tests in the given module.
1852 finder = DocTestFinder(verbose=verbose, recurse=False)
1853 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1854 for test in finder.find(f, name, globs=globs):
1855 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001856
Tim Peters8485b562004-08-04 18:46:34 +00001857######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001858## 7. Tester
Tim Peters8485b562004-08-04 18:46:34 +00001859######################################################################
1860# This is provided only for backwards compatibility. It's not
1861# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001862
Tim Peters8485b562004-08-04 18:46:34 +00001863class Tester:
1864 def __init__(self, mod=None, globs=None, verbose=None,
1865 isprivate=None, optionflags=0):
Tim Peters3ddd60a2004-08-08 02:43:33 +00001866
1867 warnings.warn("class Tester is deprecated; "
1868 "use class doctest.DocTestRunner instead",
1869 DeprecationWarning, stacklevel=2)
Tim Peters8485b562004-08-04 18:46:34 +00001870 if mod is None and globs is None:
1871 raise TypeError("Tester.__init__: must specify mod or globs")
1872 if mod is not None and not _ismodule(mod):
1873 raise TypeError("Tester.__init__: mod must be a module; %r" %
1874 (mod,))
1875 if globs is None:
1876 globs = mod.__dict__
1877 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001878
Tim Peters8485b562004-08-04 18:46:34 +00001879 self.verbose = verbose
1880 self.isprivate = isprivate
1881 self.optionflags = optionflags
Tim Petersf727c6c2004-08-08 01:48:59 +00001882 self.testfinder = DocTestFinder(_namefilter=isprivate)
Tim Peters8485b562004-08-04 18:46:34 +00001883 self.testrunner = DocTestRunner(verbose=verbose,
1884 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001885
Tim Peters8485b562004-08-04 18:46:34 +00001886 def runstring(self, s, name):
1887 test = DocTest(s, self.globs, name, None, None)
1888 if self.verbose:
1889 print "Running string", name
1890 (f,t) = self.testrunner.run(test)
1891 if self.verbose:
1892 print f, "of", t, "examples failed in string", name
1893 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001894
Tim Petersf3f57472004-08-08 06:11:48 +00001895 def rundoc(self, object, name=None, module=None):
Tim Peters8485b562004-08-04 18:46:34 +00001896 f = t = 0
1897 tests = self.testfinder.find(object, name, module=module,
Tim Petersf3f57472004-08-08 06:11:48 +00001898 globs=self.globs)
Tim Peters8485b562004-08-04 18:46:34 +00001899 for test in tests:
1900 (f2, t2) = self.testrunner.run(test)
1901 (f,t) = (f+f2, t+t2)
1902 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001903
Tim Peters8485b562004-08-04 18:46:34 +00001904 def rundict(self, d, name, module=None):
1905 import new
1906 m = new.module(name)
1907 m.__dict__.update(d)
Tim Petersf3f57472004-08-08 06:11:48 +00001908 if module is None:
1909 module = False
1910 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001911
Tim Peters8485b562004-08-04 18:46:34 +00001912 def run__test__(self, d, name):
1913 import new
1914 m = new.module(name)
1915 m.__test__ = d
1916 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001917
Tim Peters8485b562004-08-04 18:46:34 +00001918 def summarize(self, verbose=None):
1919 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001920
Tim Peters8485b562004-08-04 18:46:34 +00001921 def merge(self, other):
1922 d = self.testrunner._name2ft
1923 for name, (f, t) in other.testrunner._name2ft.items():
1924 if name in d:
1925 print "*** Tester.merge: '" + name + "' in both" \
1926 " testers; summing outcomes."
1927 f2, t2 = d[name]
1928 f = f + f2
1929 t = t + t2
1930 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001931
Tim Peters8485b562004-08-04 18:46:34 +00001932######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00001933## 8. Unittest Support
Tim Peters8485b562004-08-04 18:46:34 +00001934######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001935
Tim Peters19397e52004-08-06 22:02:59 +00001936class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001937
Edward Loper34fcb142004-08-09 02:45:41 +00001938 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
1939 checker=None):
Jim Fultona643b652004-07-14 19:06:50 +00001940 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00001941 self._dt_optionflags = optionflags
Edward Loper34fcb142004-08-09 02:45:41 +00001942 self._dt_checker = checker
Tim Peters19397e52004-08-06 22:02:59 +00001943 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()
Edward Loper34fcb142004-08-09 02:45:41 +00001959 runner = DocTestRunner(optionflags=self._dt_optionflags,
1960 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00001961
Jim Fultona643b652004-07-14 19:06:50 +00001962 try:
Tim Peters19397e52004-08-06 22:02:59 +00001963 runner.DIVIDER = "-"*70
1964 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00001965 finally:
1966 sys.stdout = old
1967
1968 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00001969 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00001970
Tim Peters19397e52004-08-06 22:02:59 +00001971 def format_failure(self, err):
1972 test = self._dt_test
1973 if test.lineno is None:
1974 lineno = 'unknown line number'
1975 else:
1976 lineno = 'line %s' % test.lineno
1977 lname = '.'.join(test.name.split('.')[-1:])
1978 return ('Failed doctest test for %s\n'
1979 ' File "%s", line %s, in %s\n\n%s'
1980 % (test.name, test.filename, lineno, lname, err)
1981 )
1982
1983 def debug(self):
1984 r"""Run the test case without results and without catching exceptions
1985
1986 The unit test framework includes a debug method on test cases
1987 and test suites to support post-mortem debugging. The test code
1988 is run in such a way that errors are not caught. This way a
1989 caller can catch the errors and initiate post-mortem debugging.
1990
1991 The DocTestCase provides a debug method that raises
1992 UnexpectedException errors if there is an unexepcted
1993 exception:
1994
1995 >>> test = DocTest('>>> raise KeyError\n42',
1996 ... {}, 'foo', 'foo.py', 0)
1997 >>> case = DocTestCase(test)
1998 >>> try:
1999 ... case.debug()
2000 ... except UnexpectedException, failure:
2001 ... pass
2002
2003 The UnexpectedException contains the test, the example, and
2004 the original exception:
2005
2006 >>> failure.test is test
2007 True
2008
2009 >>> failure.example.want
2010 '42\n'
2011
2012 >>> exc_info = failure.exc_info
2013 >>> raise exc_info[0], exc_info[1], exc_info[2]
2014 Traceback (most recent call last):
2015 ...
2016 KeyError
2017
2018 If the output doesn't match, then a DocTestFailure is raised:
2019
2020 >>> test = DocTest('''
2021 ... >>> x = 1
2022 ... >>> x
2023 ... 2
2024 ... ''', {}, 'foo', 'foo.py', 0)
2025 >>> case = DocTestCase(test)
2026
2027 >>> try:
2028 ... case.debug()
2029 ... except DocTestFailure, failure:
2030 ... pass
2031
2032 DocTestFailure objects provide access to the test:
2033
2034 >>> failure.test is test
2035 True
2036
2037 As well as to the example:
2038
2039 >>> failure.example.want
2040 '2\n'
2041
2042 and the actual output:
2043
2044 >>> failure.got
2045 '1\n'
2046
2047 """
2048
Edward Loper34fcb142004-08-09 02:45:41 +00002049 runner = DebugRunner(optionflags=self._dt_optionflags,
2050 checker=self._dt_checker, verbose=False)
Tim Peters19397e52004-08-06 22:02:59 +00002051 runner.run(self._dt_test, out=nooutput)
Jim Fultona643b652004-07-14 19:06:50 +00002052
2053 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002054 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002055
2056 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002057 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002058 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2059
2060 __str__ = __repr__
2061
2062 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002063 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002064
Tim Peters19397e52004-08-06 22:02:59 +00002065def nooutput(*args):
2066 pass
Jim Fultona643b652004-07-14 19:06:50 +00002067
Tim Peters19397e52004-08-06 22:02:59 +00002068def DocTestSuite(module=None, globs=None, extraglobs=None,
2069 optionflags=0, test_finder=None,
Edward Loper34fcb142004-08-09 02:45:41 +00002070 setUp=lambda: None, tearDown=lambda: None,
2071 checker=None):
Tim Peters8485b562004-08-04 18:46:34 +00002072 """
Tim Peters19397e52004-08-06 22:02:59 +00002073 Convert doctest tests for a mudule to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002074
Tim Peters19397e52004-08-06 22:02:59 +00002075 This converts each documentation string in a module that
2076 contains doctest tests to a unittest test case. If any of the
2077 tests in a doc string fail, then the test case fails. An exception
2078 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002079 (sometimes approximate) line number.
2080
Tim Peters19397e52004-08-06 22:02:59 +00002081 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002082 can be either a module or a module name.
2083
2084 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002085 """
Jim Fultona643b652004-07-14 19:06:50 +00002086
Tim Peters8485b562004-08-04 18:46:34 +00002087 if test_finder is None:
2088 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002089
Tim Peters19397e52004-08-06 22:02:59 +00002090 module = _normalize_module(module)
2091 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2092 if globs is None:
2093 globs = module.__dict__
2094 if not tests: # [XX] why do we want to do this?
2095 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002096
2097 tests.sort()
2098 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002099 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002100 if len(test.examples) == 0:
2101 continue
Tim Peters8485b562004-08-04 18:46:34 +00002102 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002103 filename = module.__file__
2104 if filename.endswith(".pyc"):
2105 filename = filename[:-1]
2106 elif filename.endswith(".pyo"):
2107 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002108 test.filename = filename
Edward Loper34fcb142004-08-09 02:45:41 +00002109 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown,
2110 checker))
Tim Peters19397e52004-08-06 22:02:59 +00002111
2112 return suite
2113
2114class DocFileCase(DocTestCase):
2115
2116 def id(self):
2117 return '_'.join(self._dt_test.name.split('.'))
2118
2119 def __repr__(self):
2120 return self._dt_test.filename
2121 __str__ = __repr__
2122
2123 def format_failure(self, err):
2124 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2125 % (self._dt_test.name, self._dt_test.filename, err)
2126 )
2127
2128def DocFileTest(path, package=None, globs=None,
2129 setUp=None, tearDown=None,
2130 optionflags=0):
2131 package = _normalize_module(package)
2132 name = path.split('/')[-1]
2133 dir = os.path.split(package.__file__)[0]
2134 path = os.path.join(dir, *(path.split('/')))
2135 doc = open(path).read()
2136
2137 if globs is None:
2138 globs = {}
2139
2140 test = DocTest(doc, globs, name, path, 0)
2141
2142 return DocFileCase(test, optionflags, setUp, tearDown)
2143
2144def DocFileSuite(*paths, **kw):
2145 """Creates a suite of doctest files.
2146
2147 One or more text file paths are given as strings. These should
2148 use "/" characters to separate path segments. Paths are relative
2149 to the directory of the calling module, or relative to the package
2150 passed as a keyword argument.
2151
2152 A number of options may be provided as keyword arguments:
2153
2154 package
2155 The name of a Python package. Text-file paths will be
2156 interpreted relative to the directory containing this package.
2157 The package may be supplied as a package object or as a dotted
2158 package name.
2159
2160 setUp
2161 The name of a set-up function. This is called before running the
2162 tests in each file.
2163
2164 tearDown
2165 The name of a tear-down function. This is called after running the
2166 tests in each file.
2167
2168 globs
2169 A dictionary containing initial global variables for the tests.
2170 """
2171 suite = unittest.TestSuite()
2172
2173 # We do this here so that _normalize_module is called at the right
2174 # level. If it were called in DocFileTest, then this function
2175 # would be the caller and we might guess the package incorrectly.
2176 kw['package'] = _normalize_module(kw.get('package'))
2177
2178 for path in paths:
2179 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002180
Tim Petersdb3756d2003-06-29 05:30:48 +00002181 return suite
2182
Tim Peters8485b562004-08-04 18:46:34 +00002183######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002184## 9. Debugging Support
Tim Peters8485b562004-08-04 18:46:34 +00002185######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002186
Tim Peters19397e52004-08-06 22:02:59 +00002187def script_from_examples(s):
2188 r"""Extract script from text with examples.
2189
2190 Converts text with examples to a Python script. Example input is
2191 converted to regular code. Example output and all other words
2192 are converted to comments:
2193
2194 >>> text = '''
2195 ... Here are examples of simple math.
2196 ...
2197 ... Python has super accurate integer addition
2198 ...
2199 ... >>> 2 + 2
2200 ... 5
2201 ...
2202 ... And very friendly error messages:
2203 ...
2204 ... >>> 1/0
2205 ... To Infinity
2206 ... And
2207 ... Beyond
2208 ...
2209 ... You can use logic if you want:
2210 ...
2211 ... >>> if 0:
2212 ... ... blah
2213 ... ... blah
2214 ... ...
2215 ...
2216 ... Ho hum
2217 ... '''
2218
2219 >>> print script_from_examples(text)
2220 # Here are examples of simple math.
2221 #
2222 # Python has super accurate integer addition
2223 #
2224 2 + 2
2225 # Expected:
2226 # 5
2227 #
2228 # And very friendly error messages:
2229 #
2230 1/0
2231 # Expected:
2232 # To Infinity
2233 # And
2234 # Beyond
2235 #
2236 # You can use logic if you want:
2237 #
2238 if 0:
2239 blah
2240 blah
2241 <BLANKLINE>
2242 #
2243 # Ho hum
2244 """
2245
2246 return Parser('<string>', s).get_program()
2247
Tim Peters8485b562004-08-04 18:46:34 +00002248def _want_comment(example):
2249 """
Tim Peters19397e52004-08-06 22:02:59 +00002250 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002251 """
Jim Fultona643b652004-07-14 19:06:50 +00002252 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002253 want = example.want
2254 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002255 if want[-1] == '\n':
2256 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002257 want = "\n# ".join(want.split("\n"))
2258 want = "\n# Expected:\n# %s" % want
2259 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002260
2261def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002262 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002263
2264 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002265 test to be debugged and the name (within the module) of the object
2266 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002267 """
Tim Peters8485b562004-08-04 18:46:34 +00002268 module = _normalize_module(module)
2269 tests = DocTestFinder().find(module)
2270 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002271 if not test:
2272 raise ValueError(name, "not found in tests")
2273 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002274 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002275 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002276
Jim Fultona643b652004-07-14 19:06:50 +00002277def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002278 """Debug a single doctest docstring, in argument `src`'"""
2279 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002280 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002281
Jim Fultona643b652004-07-14 19:06:50 +00002282def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002283 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002284 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002285
Tim Petersdb3756d2003-06-29 05:30:48 +00002286 srcfilename = tempfile.mktemp("doctestdebug.py")
Tim Peters8485b562004-08-04 18:46:34 +00002287 f = open(srcfilename, 'w')
2288 f.write(src)
2289 f.close()
2290
Jim Fultona643b652004-07-14 19:06:50 +00002291 if globs:
2292 globs = globs.copy()
2293 else:
2294 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002295
Tim Peters8485b562004-08-04 18:46:34 +00002296 if pm:
2297 try:
2298 execfile(srcfilename, globs, globs)
2299 except:
2300 print sys.exc_info()[1]
2301 pdb.post_mortem(sys.exc_info()[2])
2302 else:
2303 # Note that %r is vital here. '%s' instead can, e.g., cause
2304 # backslashes to get treated as metacharacters on Windows.
2305 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002306
Jim Fultona643b652004-07-14 19:06:50 +00002307def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002308 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002309
2310 Provide the module (or dotted name of the module) containing the
2311 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002312 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002313 """
Tim Peters8485b562004-08-04 18:46:34 +00002314 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002315 testsrc = testsource(module, name)
2316 debug_script(testsrc, pm, module.__dict__)
2317
Tim Peters8485b562004-08-04 18:46:34 +00002318######################################################################
Edward Loper7c748462004-08-09 02:06:06 +00002319## 10. Example Usage
Tim Peters8485b562004-08-04 18:46:34 +00002320######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002321class _TestClass:
2322 """
2323 A pointless class, for sanity-checking of docstring testing.
2324
2325 Methods:
2326 square()
2327 get()
2328
2329 >>> _TestClass(13).get() + _TestClass(-12).get()
2330 1
2331 >>> hex(_TestClass(13).square().get())
2332 '0xa9'
2333 """
2334
2335 def __init__(self, val):
2336 """val -> _TestClass object with associated value val.
2337
2338 >>> t = _TestClass(123)
2339 >>> print t.get()
2340 123
2341 """
2342
2343 self.val = val
2344
2345 def square(self):
2346 """square() -> square TestClass's associated value
2347
2348 >>> _TestClass(13).square().get()
2349 169
2350 """
2351
2352 self.val = self.val ** 2
2353 return self
2354
2355 def get(self):
2356 """get() -> return TestClass's associated value.
2357
2358 >>> x = _TestClass(-42)
2359 >>> print x.get()
2360 -42
2361 """
2362
2363 return self.val
2364
2365__test__ = {"_TestClass": _TestClass,
2366 "string": r"""
2367 Example of a string object, searched as-is.
2368 >>> x = 1; y = 2
2369 >>> x + y, x * y
2370 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002371 """,
2372 "bool-int equivalence": r"""
2373 In 2.2, boolean expressions displayed
2374 0 or 1. By default, we still accept
2375 them. This can be disabled by passing
2376 DONT_ACCEPT_TRUE_FOR_1 to the new
2377 optionflags argument.
2378 >>> 4 == 4
2379 1
2380 >>> 4 == 4
2381 True
2382 >>> 4 > 4
2383 0
2384 >>> 4 > 4
2385 False
2386 """,
Tim Peters8485b562004-08-04 18:46:34 +00002387 "blank lines": r"""
2388 Blank lines can be marked with <BLANKLINE>:
2389 >>> print 'foo\n\nbar\n'
2390 foo
2391 <BLANKLINE>
2392 bar
2393 <BLANKLINE>
2394 """,
2395 }
2396# "ellipsis": r"""
2397# If the ellipsis flag is used, then '...' can be used to
2398# elide substrings in the desired output:
2399# >>> print range(1000)
2400# [0, 1, 2, ..., 999]
2401# """,
2402# "whitespace normalization": r"""
2403# If the whitespace normalization flag is used, then
2404# differences in whitespace are ignored.
2405# >>> print range(30)
2406# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2407# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2408# 27, 28, 29]
2409# """,
2410# }
2411
2412def test1(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002413>>> warnings.filterwarnings("ignore", "class Tester", DeprecationWarning,
2414... "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002415>>> from doctest import Tester
2416>>> t = Tester(globs={'x': 42}, verbose=0)
2417>>> t.runstring(r'''
2418... >>> x = x * 2
2419... >>> print x
2420... 42
2421... ''', 'XYZ')
2422**********************************************************************
2423Failure in example: print x
2424from line #2 of XYZ
2425Expected: 42
2426Got: 84
2427(1, 2)
2428>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2429(0, 2)
2430>>> t.summarize()
2431**********************************************************************
24321 items had failures:
2433 1 of 2 in XYZ
2434***Test Failed*** 1 failures.
2435(1, 4)
2436>>> t.summarize(verbose=1)
24371 items passed all tests:
2438 2 tests in example2
2439**********************************************************************
24401 items had failures:
2441 1 of 2 in XYZ
24424 tests in 2 items.
24433 passed and 1 failed.
2444***Test Failed*** 1 failures.
2445(1, 4)
2446"""
2447
2448def test2(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002449 >>> warnings.filterwarnings("ignore", "class Tester",
2450 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002451 >>> t = Tester(globs={}, verbose=1)
2452 >>> test = r'''
2453 ... # just an example
2454 ... >>> x = 1 + 2
2455 ... >>> x
2456 ... 3
2457 ... '''
2458 >>> t.runstring(test, "Example")
2459 Running string Example
2460 Trying: x = 1 + 2
2461 Expecting: nothing
2462 ok
2463 Trying: x
2464 Expecting: 3
2465 ok
2466 0 of 2 examples failed in string Example
2467 (0, 2)
2468"""
2469def test3(): r"""
Tim Peters3ddd60a2004-08-08 02:43:33 +00002470 >>> warnings.filterwarnings("ignore", "class Tester",
2471 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002472 >>> t = Tester(globs={}, verbose=0)
2473 >>> def _f():
2474 ... '''Trivial docstring example.
2475 ... >>> assert 2 == 2
2476 ... '''
2477 ... return 32
2478 ...
2479 >>> t.rundoc(_f) # expect 0 failures in 1 example
2480 (0, 1)
2481"""
2482def test4(): """
2483 >>> import new
2484 >>> m1 = new.module('_m1')
2485 >>> m2 = new.module('_m2')
2486 >>> test_data = \"""
2487 ... def _f():
2488 ... '''>>> assert 1 == 1
2489 ... '''
2490 ... def g():
2491 ... '''>>> assert 2 != 1
2492 ... '''
2493 ... class H:
2494 ... '''>>> assert 2 > 1
2495 ... '''
2496 ... def bar(self):
2497 ... '''>>> assert 1 < 2
2498 ... '''
2499 ... \"""
2500 >>> exec test_data in m1.__dict__
2501 >>> exec test_data in m2.__dict__
2502 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2503
2504 Tests that objects outside m1 are excluded:
2505
Tim Peters3ddd60a2004-08-08 02:43:33 +00002506 >>> warnings.filterwarnings("ignore", "class Tester",
2507 ... DeprecationWarning, "doctest", 0)
Tim Peters8485b562004-08-04 18:46:34 +00002508 >>> t = Tester(globs={}, verbose=0)
Tim Petersf727c6c2004-08-08 01:48:59 +00002509 >>> t.rundict(m1.__dict__, "rundict_test", m1) # f2 and g2 and h2 skipped
Tim Peters8485b562004-08-04 18:46:34 +00002510 (0, 4)
2511
Tim Petersf727c6c2004-08-08 01:48:59 +00002512 Once more, not excluding stuff outside m1:
Tim Peters8485b562004-08-04 18:46:34 +00002513
2514 >>> t = Tester(globs={}, verbose=0)
2515 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2516 (0, 8)
2517
2518 The exclusion of objects from outside the designated module is
2519 meant to be invoked automagically by testmod.
2520
Tim Petersf727c6c2004-08-08 01:48:59 +00002521 >>> testmod(m1, verbose=False)
2522 (0, 4)
Tim Peters8485b562004-08-04 18:46:34 +00002523"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002524
2525def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002526 #import doctest
2527 #doctest.testmod(doctest, verbose=False,
2528 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2529 # UNIFIED_DIFF)
2530 #print '~'*70
2531 r = unittest.TextTestRunner()
2532 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002533
2534if __name__ == "__main__":
2535 _test()