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