blob: ff068a1aea6ede43f80d6b6ded89aaab5f346a87 [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
310from StringIO import StringIO
Tim Peters7402f792001-10-02 03:53:41 +0000311
Tim Peters6ebe61f2003-06-27 20:48:05 +0000312# Option constants.
313DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
Tim Peters8485b562004-08-04 18:46:34 +0000314DONT_ACCEPT_BLANKLINE = 1 << 1
315NORMALIZE_WHITESPACE = 1 << 2
316ELLIPSIS = 1 << 3
317UNIFIED_DIFF = 1 << 4
318CONTEXT_DIFF = 1 << 5
Tim Peters6ebe61f2003-06-27 20:48:05 +0000319
Tim Peters8485b562004-08-04 18:46:34 +0000320OPTIONFLAGS_BY_NAME = {
321 'DONT_ACCEPT_TRUE_FOR_1': DONT_ACCEPT_TRUE_FOR_1,
322 'DONT_ACCEPT_BLANKLINE': DONT_ACCEPT_BLANKLINE,
323 'NORMALIZE_WHITESPACE': NORMALIZE_WHITESPACE,
324 'ELLIPSIS': ELLIPSIS,
325 'UNIFIED_DIFF': UNIFIED_DIFF,
326 'CONTEXT_DIFF': CONTEXT_DIFF,
327 }
Tim Peters8a7d2d52001-01-16 07:10:57 +0000328
Tim Peters8485b562004-08-04 18:46:34 +0000329# Special string markers for use in `want` strings:
330BLANKLINE_MARKER = '<BLANKLINE>'
331ELLIPSIS_MARKER = '...'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000332
Tim Peters19397e52004-08-06 22:02:59 +0000333
334# There are 4 basic classes:
335# - Example: a <source, want> pair, plus an intra-docstring line number.
336# - DocTest: a collection of examples, parsed from a docstring, plus
337# info about where the docstring came from (name, filename, lineno).
338# - DocTestFinder: extracts DocTests from a given object's docstring and
339# its contained objects' docstrings.
340# - DocTestRunner: runs DocTest cases, and accumulates statistics.
341#
342# So the basic picture is:
343#
344# list of:
345# +------+ +---------+ +-------+
346# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
347# +------+ +---------+ +-------+
348# | Example |
349# | ... |
350# | Example |
351# +---------+
352
Tim Peters8485b562004-08-04 18:46:34 +0000353######################################################################
354## Table of Contents
355######################################################################
356# 1. Utility Functions
357# 2. Example & DocTest -- store test cases
358# 3. DocTest Finder -- extracts test cases from objects
359# 4. DocTest Runner -- runs test cases
360# 5. Test Functions -- convenient wrappers for testing
361# 6. Tester Class -- for backwards compatibility
362# 7. Unittest Support
363# 8. Debugging Support
364# 9. Example Usage
Tim Peters8a7d2d52001-01-16 07:10:57 +0000365
Tim Peters8485b562004-08-04 18:46:34 +0000366######################################################################
367## 1. Utility Functions
368######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +0000369
370def is_private(prefix, base):
371 """prefix, base -> true iff name prefix + "." + base is "private".
372
373 Prefix may be an empty string, and base does not contain a period.
374 Prefix is ignored (although functions you write conforming to this
375 protocol may make use of it).
376 Return true iff base begins with an (at least one) underscore, but
377 does not both begin and end with (at least) two underscores.
378
379 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000380 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000381 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000382 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000383 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000384 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000385 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000386 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000387 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000388 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000389 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000390 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000391 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000392 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000393 """
Tim Peters8a7d2d52001-01-16 07:10:57 +0000394 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
395
Tim Peters8485b562004-08-04 18:46:34 +0000396def _extract_future_flags(globs):
397 """
398 Return the compiler-flags associated with the future features that
399 have been imported into the given namespace (globs).
400 """
401 flags = 0
402 for fname in __future__.all_feature_names:
403 feature = globs.get(fname, None)
404 if feature is getattr(__future__, fname):
405 flags |= feature.compiler_flag
406 return flags
Tim Peters7402f792001-10-02 03:53:41 +0000407
Tim Peters8485b562004-08-04 18:46:34 +0000408def _normalize_module(module, depth=2):
409 """
410 Return the module specified by `module`. In particular:
411 - If `module` is a module, then return module.
412 - If `module` is a string, then import and return the
413 module with that name.
414 - If `module` is None, then return the calling module.
415 The calling module is assumed to be the module of
416 the stack frame at the given depth in the call stack.
417 """
418 if inspect.ismodule(module):
419 return module
420 elif isinstance(module, (str, unicode)):
421 return __import__(module, globals(), locals(), ["*"])
422 elif module is None:
423 return sys.modules[sys._getframe(depth).f_globals['__name__']]
424 else:
425 raise TypeError("Expected a module, string, or None")
Tim Peters7402f792001-10-02 03:53:41 +0000426
Tim Peters8485b562004-08-04 18:46:34 +0000427def _tag_msg(tag, msg, indent_msg=True):
428 """
429 Return a string that displays a tag-and-message pair nicely,
430 keeping the tag and its message on the same line when that
431 makes sense. If `indent_msg` is true, then messages that are
432 put on separate lines will be indented.
433 """
434 # What string should we use to indent contents?
435 INDENT = ' '
Tim Peters8a7d2d52001-01-16 07:10:57 +0000436
Tim Peters8485b562004-08-04 18:46:34 +0000437 # If the message doesn't end in a newline, then add one.
438 if msg[-1:] != '\n':
439 msg += '\n'
440 # If the message is short enough, and contains no internal
441 # newlines, then display it on the same line as the tag.
442 # Otherwise, display the tag on its own line.
443 if (len(tag) + len(msg) < 75 and
444 msg.find('\n', 0, len(msg)-1) == -1):
445 return '%s: %s' % (tag, msg)
446 else:
447 if indent_msg:
448 msg = '\n'.join([INDENT+l for l in msg.split('\n')])
449 msg = msg[:-len(INDENT)]
450 return '%s:\n%s' % (tag, msg)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000451
Tim Peters8485b562004-08-04 18:46:34 +0000452# Override some StringIO methods.
453class _SpoofOut(StringIO):
454 def getvalue(self):
455 result = StringIO.getvalue(self)
456 # If anything at all was written, make sure there's a trailing
457 # newline. There's no way for the expected output to indicate
458 # that a trailing newline is missing.
459 if result and not result.endswith("\n"):
460 result += "\n"
461 # Prevent softspace from screwing up the next test case, in
462 # case they used print with a trailing comma in an example.
463 if hasattr(self, "softspace"):
464 del self.softspace
465 return result
Tim Peters8a7d2d52001-01-16 07:10:57 +0000466
Tim Peters8485b562004-08-04 18:46:34 +0000467 def truncate(self, size=None):
468 StringIO.truncate(self, size)
469 if hasattr(self, "softspace"):
470 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000471
Tim Peters19397e52004-08-06 22:02:59 +0000472class Parser:
473 """
474 Extract doctests from a string.
475 """
476
477 _PS1 = ">>>"
478 _PS2 = "..."
479 _isPS1 = re.compile(r"(\s*)" + re.escape(_PS1)).match
480 _isPS2 = re.compile(r"(\s*)" + re.escape(_PS2)).match
481 _isEmpty = re.compile(r"\s*$").match
482 _isComment = re.compile(r"\s*#").match
483
484 def __init__(self, name, string):
485 """
486 Prepare to extract doctests from string `string`.
487
488 `name` is an arbitrary (string) name associated with the string,
489 and is used only in error messages.
490 """
491 self.name = name
492 self.source = string
493
494 def get_examples(self):
495 """
496 Return the doctest examples from the string.
497
498 This is a list of (source, want, lineno) triples, one per example
499 in the string. "source" is a single Python statement; it ends
500 with a newline iff the statement contains more than one
501 physical line. "want" is the expected output from running the
502 example (either from stdout, or a traceback in case of exception).
503 "want" always ends with a newline, unless no output is expected,
504 in which case "want" is an empty string. "lineno" is the 0-based
505 line number of the first line of "source" within the string. It's
506 0-based because it's most common in doctests that nothing
507 interesting appears on the same line as opening triple-quote,
508 and so the first interesting line is called "line 1" then.
509
510 >>> text = '''
511 ... >>> x, y = 2, 3 # no output expected
512 ... >>> if 1:
513 ... ... print x
514 ... ... print y
515 ... 2
516 ... 3
517 ...
518 ... Some text.
519 ... >>> x+y
520 ... 5
521 ... '''
522 >>> for x in Parser('<string>', text).get_examples():
523 ... print x
524 ('x, y = 2, 3 # no output expected', '', 1)
525 ('if 1:\\n print x\\n print y\\n', '2\\n3\\n', 2)
526 ('x+y', '5\\n', 9)
527 """
528 return self._parse(kind='examples')
529
530 def get_program(self):
531 """
532 Return an executable program from the string, as a string.
533
534 The format of this isn't rigidly defined. In general, doctest
535 examples become the executable statements in the result, and
536 their expected outputs become comments, preceded by an "#Expected:"
537 comment. Everything else (text, comments, everything not part of
538 a doctest test) is also placed in comments.
539
540 >>> text = '''
541 ... >>> x, y = 2, 3 # no output expected
542 ... >>> if 1:
543 ... ... print x
544 ... ... print y
545 ... 2
546 ... 3
547 ...
548 ... Some text.
549 ... >>> x+y
550 ... 5
551 ... '''
552 >>> print Parser('<string>', text).get_program()
553 x, y = 2, 3 # no output expected
554 if 1:
555 print x
556 print y
557 # Expected:
558 # 2
559 # 3
560 #
561 # Some text.
562 x+y
563 # Expected:
564 # 5
565 """
566 return self._parse(kind='program')
567
568 def _parse(self, kind):
569 assert kind in ('examples', 'program')
570 do_program = kind == 'program'
571 output = []
572 push = output.append
573
574 string = self.source
575 if not string.endswith('\n'):
576 string += '\n'
577
578 isPS1, isPS2 = self._isPS1, self._isPS2
579 isEmpty, isComment = self._isEmpty, self._isComment
580 lines = string.split("\n")
581 i, n = 0, len(lines)
582 while i < n:
583 # Search for an example (a PS1 line).
584 line = lines[i]
585 i += 1
586 m = isPS1(line)
587 if m is None:
588 if do_program:
589 line = line.rstrip()
590 if line:
591 line = ' ' + line
592 push('#' + line)
593 continue
594 # line is a PS1 line.
595 j = m.end(0) # beyond the prompt
596 if isEmpty(line, j) or isComment(line, j):
597 # a bare prompt or comment -- not interesting
598 if do_program:
599 push("# " + line[j:])
600 continue
601 # line is a non-trivial PS1 line.
602 lineno = i - 1
603 if line[j] != " ":
604 raise ValueError('line %r of the docstring for %s lacks '
605 'blank after %s: %r' %
606 (lineno, self.name, self._PS1, line))
607
608 j += 1
609 blanks = m.group(1)
610 nblanks = len(blanks)
611 # suck up this and following PS2 lines
612 source = []
613 while 1:
614 source.append(line[j:])
615 line = lines[i]
616 m = isPS2(line)
617 if m:
618 if m.group(1) != blanks:
619 raise ValueError('line %r of the docstring for %s '
620 'has inconsistent leading whitespace: %r' %
621 (i, self.name, line))
622 i += 1
623 else:
624 break
625
626 if do_program:
627 output.extend(source)
628 else:
629 # get rid of useless null line from trailing empty "..."
630 if source[-1] == "":
631 assert len(source) > 1
632 del source[-1]
633 if len(source) == 1:
634 source = source[0]
635 else:
636 source = "\n".join(source) + "\n"
637
638 # suck up response
639 if isPS1(line) or isEmpty(line):
640 if not do_program:
641 push((source, "", lineno))
642 continue
643
644 # There is a response.
645 want = []
646 if do_program:
647 push("# Expected:")
648 while 1:
649 if line[:nblanks] != blanks:
650 raise ValueError('line %r of the docstring for %s '
651 'has inconsistent leading whitespace: %r' %
652 (i, self.name, line))
653 want.append(line[nblanks:])
654 i += 1
655 line = lines[i]
656 if isPS1(line) or isEmpty(line):
657 break
658
659 if do_program:
660 output.extend(['# ' + x for x in want])
661 else:
662 want = "\n".join(want) + "\n"
663 push((source, want, lineno))
664
665 if do_program:
666 # Trim junk on both ends.
667 while output and output[-1] == '#':
668 output.pop()
669 while output and output[0] == '#':
670 output.pop(0)
671 output = '\n'.join(output)
672
673 return output
674
Tim Peters8485b562004-08-04 18:46:34 +0000675######################################################################
676## 2. Example & DocTest
677######################################################################
678## - An "example" is a <source, want> pair, where "source" is a
679## fragment of source code, and "want" is the expected output for
680## "source." The Example class also includes information about
681## where the example was extracted from.
682##
683## - A "doctest" is a collection of examples extracted from a string
684## (such as an object's docstring). The DocTest class also includes
685## information about where the string was extracted from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000686
Tim Peters8485b562004-08-04 18:46:34 +0000687class Example:
688 """
689 A single doctest example, consisting of source code and expected
690 output. Example defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000691
Tim Peters8485b562004-08-04 18:46:34 +0000692 - source: The source code that should be run. It ends with a
693 newline iff the source spans more than one line.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000694
Tim Peters8485b562004-08-04 18:46:34 +0000695 - want: The expected output from running the source code. If
696 not empty, then this string ends with a newline.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000697
Tim Peters8485b562004-08-04 18:46:34 +0000698 - lineno: The line number within the DocTest string containing
699 this Example where the Example begins. This line number is
700 zero-based, with respect to the beginning of the DocTest.
701 """
702 def __init__(self, source, want, lineno):
703 # Check invariants.
Tim Peters9b625d32004-08-04 20:04:32 +0000704 if (source[-1:] == '\n') != ('\n' in source[:-1]):
705 raise AssertionError("source must end with newline iff "
706 "source contains more than one line")
707 if want and want[-1] != '\n':
708 raise AssertionError("non-empty want must end with newline")
Tim Peters8485b562004-08-04 18:46:34 +0000709 # Store properties.
710 self.source = source
711 self.want = want
712 self.lineno = lineno
Tim Peters8a7d2d52001-01-16 07:10:57 +0000713
Tim Peters8485b562004-08-04 18:46:34 +0000714class DocTest:
715 """
716 A collection of doctest examples that should be run in a single
717 namespace. Each DocTest defines the following attributes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000718
Tim Peters8485b562004-08-04 18:46:34 +0000719 - examples: the list of examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000720
Tim Peters8485b562004-08-04 18:46:34 +0000721 - globs: The namespace (aka globals) that the examples should
722 be run in.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000723
Tim Peters8485b562004-08-04 18:46:34 +0000724 - name: A name identifying the DocTest (typically, the name of
725 the object whose docstring this DocTest was extracted from).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000726
Tim Peters19397e52004-08-06 22:02:59 +0000727 - docstring: The docstring being tested
728
Tim Peters8485b562004-08-04 18:46:34 +0000729 - filename: The name of the file that this DocTest was extracted
730 from.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000731
Tim Peters8485b562004-08-04 18:46:34 +0000732 - lineno: The line number within filename where this DocTest
733 begins. This line number is zero-based, with respect to the
734 beginning of the file.
735 """
736 def __init__(self, docstring, globs, name, filename, lineno):
737 """
738 Create a new DocTest, by extracting examples from `docstring`.
739 The DocTest's globals are initialized with a copy of `globs`.
740 """
741 # Store a copy of the globals
742 self.globs = globs.copy()
743 # Store identifying information
744 self.name = name
745 self.filename = filename
746 self.lineno = lineno
747 # Parse the docstring.
Tim Peters19397e52004-08-06 22:02:59 +0000748 self.docstring = docstring
749 examples = Parser(name, docstring).get_examples()
750 self.examples = [Example(*example) for example in examples]
Tim Peters8485b562004-08-04 18:46:34 +0000751
752 def __repr__(self):
753 if len(self.examples) == 0:
754 examples = 'no examples'
755 elif len(self.examples) == 1:
756 examples = '1 example'
757 else:
758 examples = '%d examples' % len(self.examples)
759 return ('<DocTest %s from %s:%s (%s)>' %
760 (self.name, self.filename, self.lineno, examples))
761
762
763 # This lets us sort tests by name:
764 def __cmp__(self, other):
765 if not isinstance(other, DocTest):
766 return -1
767 return cmp((self.name, self.filename, self.lineno, id(self)),
768 (other.name, other.filename, other.lineno, id(other)))
769
770######################################################################
771## 3. DocTest Finder
772######################################################################
773
774class DocTestFinder:
775 """
776 A class used to extract the DocTests that are relevant to a given
777 object, from its docstring and the docstrings of its contained
778 objects. Doctests can currently be extracted from the following
779 object types: modules, functions, classes, methods, staticmethods,
780 classmethods, and properties.
781
782 An optional name filter and an optional object filter may be
783 passed to the constructor, to restrict which contained objects are
784 examined by the doctest finder:
785
786 - The name filter is a function `f(prefix, base)`, that returns
787 true if an object named `prefix.base` should be ignored.
788 - The object filter is a function `f(obj)` that returns true
789 if the given object should be ignored.
790
791 Each object is ignored if either filter function returns true for
792 that object. These filter functions are applied when examining
793 the contents of a module or of a class, but not when examining a
794 module's `__test__` dictionary. By default, no objects are
795 ignored.
796 """
797
Tim Peters19397e52004-08-06 22:02:59 +0000798 def __init__(self, verbose=False, doctest_factory=DocTest,
799 namefilter=None, objfilter=None, recurse=True):
Tim Peters8485b562004-08-04 18:46:34 +0000800 """
801 Create a new doctest finder.
802
Tim Peters19397e52004-08-06 22:02:59 +0000803 The optional argument `doctest_factory` specifies a class or
804 function that should be used to create new DocTest objects (or
805 objects that implement the same interface as DocTest). This
806 signature for this factory function should match the signature
807 of the DocTest constructor.
808
Tim Peters8485b562004-08-04 18:46:34 +0000809 If the optional argument `recurse` is false, then `find` will
810 only examine the given object, and not any contained objects.
811 """
Tim Peters19397e52004-08-06 22:02:59 +0000812 self._doctest_factory = doctest_factory
Tim Peters8485b562004-08-04 18:46:34 +0000813 self._verbose = verbose
814 self._namefilter = namefilter
815 self._objfilter = objfilter
816 self._recurse = recurse
817
818 def find(self, obj, name=None, module=None, globs=None,
819 extraglobs=None, ignore_imports=True):
820 """
821 Return a list of the DocTests that are defined by the given
822 object's docstring, or by any of its contained objects'
823 docstrings.
824
825 The optional parameter `module` is the module that contains
826 the given object. If the module is not specified, then the
827 test finder will attempt to automatically determine the
828 correct module. The object's module is used:
829
830 - As a default namespace, if `globs` is not specified.
831 - To prevent the DocTestFinder from extracting DocTests
832 from objects that are imported from other modules
833 (as long as `ignore_imports` is true).
834 - To find the name of the file containing the object.
835 - To help find the line number of the object within its
836 file.
837
838 The globals for each DocTest is formed by combining `globs`
839 and `extraglobs` (bindings in `extraglobs` override bindings
840 in `globs`). A new copy of the globals dictionary is created
841 for each DocTest. If `globs` is not specified, then it
842 defaults to the module's `__dict__`, if specified, or {}
843 otherwise. If `extraglobs` is not specified, then it defaults
844 to {}.
845
846 If the optional flag `ignore_imports` is true, then the
847 doctest finder will ignore any contained objects whose module
848 does not match `module`. Otherwise, it will extract tests
849 from all contained objects, including imported objects.
850 """
851 # If name was not specified, then extract it from the object.
852 if name is None:
853 name = getattr(obj, '__name__', None)
854 if name is None:
855 raise ValueError("DocTestFinder.find: name must be given "
856 "when obj.__name__ doesn't exist: %r" %
857 (type(obj),))
858
859 # Find the module that contains the given object (if obj is
860 # a module, then module=obj.). Note: this may fail, in which
861 # case module will be None.
862 if module is None:
863 module = inspect.getmodule(obj)
864
865 # Read the module's source code. This is used by
866 # DocTestFinder._find_lineno to find the line number for a
867 # given object's docstring.
868 try:
869 file = inspect.getsourcefile(obj) or inspect.getfile(obj)
870 source_lines = linecache.getlines(file)
871 if not source_lines:
872 source_lines = None
873 except TypeError:
874 source_lines = None
875
876 # Initialize globals, and merge in extraglobs.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000877 if globs is None:
Tim Peters8485b562004-08-04 18:46:34 +0000878 if module is None:
879 globs = {}
880 else:
881 globs = module.__dict__.copy()
882 else:
883 globs = globs.copy()
884 if extraglobs is not None:
885 globs.update(extraglobs)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000886
Tim Peters8485b562004-08-04 18:46:34 +0000887 # Recursively expore `obj`, extracting DocTests.
888 tests = []
889 self._find(tests, obj, name, module, source_lines,
890 globs, ignore_imports, {})
891 return tests
892
893 def _filter(self, obj, prefix, base):
894 """
895 Return true if the given object should not be examined.
896 """
897 return ((self._namefilter is not None and
898 self._namefilter(prefix, base)) or
899 (self._objfilter is not None and
900 self._objfilter(obj)))
901
902 def _from_module(self, module, object):
903 """
904 Return true if the given object is defined in the given
905 module.
906 """
907 if module is None:
908 return True
909 elif inspect.isfunction(object):
910 return module.__dict__ is object.func_globals
911 elif inspect.isclass(object):
912 return module.__name__ == object.__module__
913 elif inspect.getmodule(object) is not None:
914 return module is inspect.getmodule(object)
915 elif hasattr(object, '__module__'):
916 return module.__name__ == object.__module__
917 elif isinstance(object, property):
918 return True # [XX] no way not be sure.
919 else:
920 raise ValueError("object must be a class or function")
921
922 def _find(self, tests, obj, name, module, source_lines,
923 globs, ignore_imports, seen):
924 """
925 Find tests for the given object and any contained objects, and
926 add them to `tests`.
927 """
928 if self._verbose:
929 print 'Finding tests in %s' % name
930
931 # If we've already processed this object, then ignore it.
932 if id(obj) in seen:
933 return
934 seen[id(obj)] = 1
935
936 # Find a test for this object, and add it to the list of tests.
937 test = self._get_test(obj, name, module, globs, source_lines)
938 if test is not None:
939 tests.append(test)
940
941 # Look for tests in a module's contained objects.
942 if inspect.ismodule(obj) and self._recurse:
943 for valname, val in obj.__dict__.items():
944 # Check if this contained object should be ignored.
945 if self._filter(val, name, valname):
946 continue
947 valname = '%s.%s' % (name, valname)
948 # Recurse to functions & classes.
949 if ((inspect.isfunction(val) or inspect.isclass(val)) and
950 (self._from_module(module, val) or not ignore_imports)):
951 self._find(tests, val, valname, module, source_lines,
952 globs, ignore_imports, seen)
953
954 # Look for tests in a module's __test__ dictionary.
955 if inspect.ismodule(obj) and self._recurse:
956 for valname, val in getattr(obj, '__test__', {}).items():
957 if not isinstance(valname, basestring):
958 raise ValueError("DocTestFinder.find: __test__ keys "
959 "must be strings: %r" %
960 (type(valname),))
961 if not (inspect.isfunction(val) or inspect.isclass(val) or
962 inspect.ismethod(val) or inspect.ismodule(val) or
963 isinstance(val, basestring)):
964 raise ValueError("DocTestFinder.find: __test__ values "
965 "must be strings, functions, methods, "
966 "classes, or modules: %r" %
967 (type(val),))
968 valname = '%s.%s' % (name, valname)
969 self._find(tests, val, valname, module, source_lines,
970 globs, ignore_imports, seen)
971
972 # Look for tests in a class's contained objects.
973 if inspect.isclass(obj) and self._recurse:
974 for valname, val in obj.__dict__.items():
975 # Check if this contained object should be ignored.
976 if self._filter(val, name, valname):
977 continue
978 # Special handling for staticmethod/classmethod.
979 if isinstance(val, staticmethod):
980 val = getattr(obj, valname)
981 if isinstance(val, classmethod):
982 val = getattr(obj, valname).im_func
983
984 # Recurse to methods, properties, and nested classes.
985 if ((inspect.isfunction(val) or inspect.isclass(val) or
986 isinstance(val, property)) and
987 (self._from_module(module, val) or not ignore_imports)):
988 valname = '%s.%s' % (name, valname)
989 self._find(tests, val, valname, module, source_lines,
990 globs, ignore_imports, seen)
991
992 def _get_test(self, obj, name, module, globs, source_lines):
993 """
994 Return a DocTest for the given object, if it defines a docstring;
995 otherwise, return None.
996 """
997 # Extract the object's docstring. If it doesn't have one,
998 # then return None (no test for this object).
999 if isinstance(obj, basestring):
1000 docstring = obj
1001 else:
1002 try:
1003 if obj.__doc__ is None:
1004 return None
1005 docstring = str(obj.__doc__)
1006 except (TypeError, AttributeError):
1007 return None
1008
1009 # Don't bother if the docstring is empty.
1010 if not docstring:
1011 return None
1012
1013 # Find the docstring's location in the file.
1014 lineno = self._find_lineno(obj, source_lines)
1015
1016 # Return a DocTest for this object.
1017 if module is None:
1018 filename = None
1019 else:
1020 filename = getattr(module, '__file__', module.__name__)
Tim Peters19397e52004-08-06 22:02:59 +00001021 return self._doctest_factory(docstring, globs, name, filename, lineno)
Tim Peters8485b562004-08-04 18:46:34 +00001022
1023 def _find_lineno(self, obj, source_lines):
1024 """
1025 Return a line number of the given object's docstring. Note:
1026 this method assumes that the object has a docstring.
1027 """
1028 lineno = None
1029
1030 # Find the line number for modules.
1031 if inspect.ismodule(obj):
1032 lineno = 0
1033
1034 # Find the line number for classes.
1035 # Note: this could be fooled if a class is defined multiple
1036 # times in a single file.
1037 if inspect.isclass(obj):
1038 if source_lines is None:
1039 return None
1040 pat = re.compile(r'^\s*class\s*%s\b' %
1041 getattr(obj, '__name__', '-'))
1042 for i, line in enumerate(source_lines):
1043 if pat.match(line):
1044 lineno = i
1045 break
1046
1047 # Find the line number for functions & methods.
1048 if inspect.ismethod(obj): obj = obj.im_func
1049 if inspect.isfunction(obj): obj = obj.func_code
1050 if inspect.istraceback(obj): obj = obj.tb_frame
1051 if inspect.isframe(obj): obj = obj.f_code
1052 if inspect.iscode(obj):
1053 lineno = getattr(obj, 'co_firstlineno', None)-1
1054
1055 # Find the line number where the docstring starts. Assume
1056 # that it's the first line that begins with a quote mark.
1057 # Note: this could be fooled by a multiline function
1058 # signature, where a continuation line begins with a quote
1059 # mark.
1060 if lineno is not None:
1061 if source_lines is None:
1062 return lineno+1
1063 pat = re.compile('(^|.*:)\s*\w*("|\')')
1064 for lineno in range(lineno, len(source_lines)):
1065 if pat.match(source_lines[lineno]):
1066 return lineno
1067
1068 # We couldn't find the line number.
1069 return None
1070
1071######################################################################
1072## 4. DocTest Runner
1073######################################################################
1074
1075# [XX] Should overridable methods (eg DocTestRunner.check_output) be
1076# named with a leading underscore?
1077
1078class DocTestRunner:
1079 """
1080 A class used to run DocTest test cases, and accumulate statistics.
1081 The `run` method is used to process a single DocTest case. It
1082 returns a tuple `(f, t)`, where `t` is the number of test cases
1083 tried, and `f` is the number of test cases that failed.
1084
1085 >>> tests = DocTestFinder().find(_TestClass)
1086 >>> runner = DocTestRunner(verbose=False)
1087 >>> for test in tests:
1088 ... print runner.run(test)
1089 (0, 2)
1090 (0, 1)
1091 (0, 2)
1092 (0, 2)
1093
1094 The `summarize` method prints a summary of all the test cases that
1095 have been run by the runner, and returns an aggregated `(f, t)`
1096 tuple:
1097
1098 >>> runner.summarize(verbose=1)
1099 4 items passed all tests:
1100 2 tests in _TestClass
1101 2 tests in _TestClass.__init__
1102 2 tests in _TestClass.get
1103 1 tests in _TestClass.square
1104 7 tests in 4 items.
1105 7 passed and 0 failed.
1106 Test passed.
1107 (0, 7)
1108
1109 The aggregated number of tried examples and failed examples is
1110 also available via the `tries` and `failures` attributes:
1111
1112 >>> runner.tries
1113 7
1114 >>> runner.failures
1115 0
1116
1117 The comparison between expected outputs and actual outputs is done
1118 by the `check_output` method. This comparison may be customized
1119 with a number of option flags; see the documentation for `testmod`
1120 for more information. If the option flags are insufficient, then
1121 the comparison may also be customized by subclassing
1122 DocTestRunner, and overriding the methods `check_output` and
1123 `output_difference`.
1124
1125 The test runner's display output can be controlled in two ways.
1126 First, an output function (`out) can be passed to
1127 `TestRunner.run`; this function will be called with strings that
1128 should be displayed. It defaults to `sys.stdout.write`. If
1129 capturing the output is not sufficient, then the display output
1130 can be also customized by subclassing DocTestRunner, and
1131 overriding the methods `report_start`, `report_success`,
1132 `report_unexpected_exception`, and `report_failure`.
1133 """
1134 # This divider string is used to separate failure messages, and to
1135 # separate sections of the summary.
1136 DIVIDER = "*" * 70
1137
1138 def __init__(self, verbose=None, optionflags=0):
1139 """
1140 Create a new test runner.
1141
1142 Optional keyword arg 'verbose' prints lots of stuff if true,
1143 only failures if false; by default, it's true iff '-v' is in
1144 sys.argv.
1145
1146 Optional argument `optionflags` can be used to control how the
1147 test runner compares expected output to actual output, and how
1148 it displays failures. See the documentation for `testmod` for
1149 more information.
1150 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001151 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001152 verbose = '-v' in sys.argv
1153 self._verbose = verbose
Tim Peters6ebe61f2003-06-27 20:48:05 +00001154 self.optionflags = optionflags
1155
Tim Peters8485b562004-08-04 18:46:34 +00001156 # Keep track of the examples we've run.
1157 self.tries = 0
1158 self.failures = 0
1159 self._name2ft = {}
Tim Peters8a7d2d52001-01-16 07:10:57 +00001160
Tim Peters8485b562004-08-04 18:46:34 +00001161 # Create a fake output target for capturing doctest output.
1162 self._fakeout = _SpoofOut()
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001163
Tim Peters8485b562004-08-04 18:46:34 +00001164 #/////////////////////////////////////////////////////////////////
1165 # Output verification methods
1166 #/////////////////////////////////////////////////////////////////
1167 # These two methods should be updated together, since the
1168 # output_difference method needs to know what should be considered
1169 # to match by check_output.
1170
1171 def check_output(self, want, got):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001172 """
Tim Peters8485b562004-08-04 18:46:34 +00001173 Return True iff the actual output (`got`) matches the expected
1174 output (`want`). These strings are always considered to match
1175 if they are identical; but depending on what option flags the
1176 test runner is using, several non-exact match types are also
1177 possible. See the documentation for `TestRunner` for more
1178 information about option flags.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001179 """
Tim Peters8485b562004-08-04 18:46:34 +00001180 # Handle the common case first, for efficiency:
1181 # if they're string-identical, always return true.
1182 if got == want:
1183 return True
Tim Peters8a7d2d52001-01-16 07:10:57 +00001184
Tim Peters8485b562004-08-04 18:46:34 +00001185 # The values True and False replaced 1 and 0 as the return
1186 # value for boolean comparisons in Python 2.3.
1187 if not (self.optionflags & DONT_ACCEPT_TRUE_FOR_1):
1188 if (got,want) == ("True\n", "1\n"):
1189 return True
1190 if (got,want) == ("False\n", "0\n"):
1191 return True
Tim Peters8a7d2d52001-01-16 07:10:57 +00001192
Tim Peters8485b562004-08-04 18:46:34 +00001193 # <BLANKLINE> can be used as a special sequence to signify a
1194 # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
1195 if not (self.optionflags & DONT_ACCEPT_BLANKLINE):
1196 # Replace <BLANKLINE> in want with a blank line.
1197 want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
1198 '', want)
1199 # If a line in got contains only spaces, then remove the
1200 # spaces.
1201 got = re.sub('(?m)^\s*?$', '', got)
1202 if got == want:
1203 return True
1204
1205 # This flag causes doctest to ignore any differences in the
1206 # contents of whitespace strings. Note that this can be used
1207 # in conjunction with the ELLISPIS flag.
1208 if (self.optionflags & NORMALIZE_WHITESPACE):
1209 got = ' '.join(got.split())
1210 want = ' '.join(want.split())
1211 if got == want:
1212 return True
1213
1214 # The ELLIPSIS flag says to let the sequence "..." in `want`
1215 # match any substring in `got`. We implement this by
1216 # transforming `want` into a regular expression.
1217 if (self.optionflags & ELLIPSIS):
1218 # Escape any special regexp characters
1219 want_re = re.escape(want)
1220 # Replace ellipsis markers ('...') with .*
1221 want_re = want_re.replace(re.escape(ELLIPSIS_MARKER), '.*')
1222 # Require that it matches the entire string; and set the
1223 # re.DOTALL flag (with '(?s)').
1224 want_re = '(?s)^%s$' % want_re
1225 # Check if the `want_re` regexp matches got.
1226 if re.match(want_re, got):
1227 return True
1228
1229 # We didn't find any match; return false.
1230 return False
1231
1232 def output_difference(self, want, got):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001233 """
Tim Peters8485b562004-08-04 18:46:34 +00001234 Return a string describing the differences between the
1235 expected output (`want`) and the actual output (`got`).
Tim Peters8a7d2d52001-01-16 07:10:57 +00001236 """
Tim Peters8485b562004-08-04 18:46:34 +00001237 # If <BLANKLINE>s are being used, then replace <BLANKLINE>
1238 # with blank lines in the expected output string.
1239 if not (self.optionflags & DONT_ACCEPT_BLANKLINE):
1240 want = re.sub('(?m)^%s$' % re.escape(BLANKLINE_MARKER), '', want)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001241
Tim Peters8485b562004-08-04 18:46:34 +00001242 # Check if we should use diff. Don't use diff if the actual
1243 # or expected outputs are too short, or if the expected output
1244 # contains an ellipsis marker.
1245 if ((self.optionflags & (UNIFIED_DIFF | CONTEXT_DIFF)) and
1246 want.count('\n') > 2 and got.count('\n') > 2 and
1247 not (self.optionflags & ELLIPSIS and '...' in want)):
1248 # Split want & got into lines.
1249 want_lines = [l+'\n' for l in want.split('\n')]
1250 got_lines = [l+'\n' for l in got.split('\n')]
1251 # Use difflib to find their differences.
1252 if self.optionflags & UNIFIED_DIFF:
1253 diff = difflib.unified_diff(want_lines, got_lines, n=2,
1254 fromfile='Expected', tofile='Got')
1255 kind = 'unified'
1256 elif self.optionflags & CONTEXT_DIFF:
1257 diff = difflib.context_diff(want_lines, got_lines, n=2,
1258 fromfile='Expected', tofile='Got')
1259 kind = 'context'
1260 else:
1261 assert 0, 'Bad diff option'
1262 # Remove trailing whitespace on diff output.
1263 diff = [line.rstrip() + '\n' for line in diff]
1264 return _tag_msg("Differences (" + kind + " diff)",
1265 ''.join(diff))
Tim Peters17111f32001-10-03 04:08:26 +00001266
Tim Peters8485b562004-08-04 18:46:34 +00001267 # If we're not using diff, then simply list the expected
1268 # output followed by the actual output.
1269 return (_tag_msg("Expected", want or "Nothing") +
1270 _tag_msg("Got", got))
Tim Peters17111f32001-10-03 04:08:26 +00001271
Tim Peters8485b562004-08-04 18:46:34 +00001272 #/////////////////////////////////////////////////////////////////
1273 # Reporting methods
1274 #/////////////////////////////////////////////////////////////////
Tim Peters17111f32001-10-03 04:08:26 +00001275
Tim Peters8485b562004-08-04 18:46:34 +00001276 def report_start(self, out, test, example):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001277 """
Tim Peters8485b562004-08-04 18:46:34 +00001278 Report that the test runner is about to process the given
1279 example. (Only displays a message if verbose=True)
1280 """
1281 if self._verbose:
1282 out(_tag_msg("Trying", example.source) +
1283 _tag_msg("Expecting", example.want or "nothing"))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001284
Tim Peters8485b562004-08-04 18:46:34 +00001285 def report_success(self, out, test, example, got):
1286 """
1287 Report that the given example ran successfully. (Only
1288 displays a message if verbose=True)
1289 """
1290 if self._verbose:
1291 out("ok\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001292
Tim Peters8485b562004-08-04 18:46:34 +00001293 def report_failure(self, out, test, example, got):
1294 """
1295 Report that the given example failed.
1296 """
1297 # Print an error message.
1298 out(self.__failure_header(test, example) +
1299 self.output_difference(example.want, got))
Tim Peters7402f792001-10-02 03:53:41 +00001300
Tim Peters8485b562004-08-04 18:46:34 +00001301 def report_unexpected_exception(self, out, test, example, exc_info):
1302 """
1303 Report that the given example raised an unexpected exception.
1304 """
1305 # Get a traceback message.
1306 excout = StringIO()
1307 exc_type, exc_val, exc_tb = exc_info
1308 traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
1309 exception_tb = excout.getvalue()
1310 # Print an error message.
1311 out(self.__failure_header(test, example) +
1312 _tag_msg("Exception raised", exception_tb))
Tim Peters7402f792001-10-02 03:53:41 +00001313
Tim Peters8485b562004-08-04 18:46:34 +00001314 def __failure_header(self, test, example):
1315 s = (self.DIVIDER + "\n" +
1316 _tag_msg("Failure in example", example.source))
1317 if test.filename is None:
1318 # [XX] I'm not putting +1 here, to give the same output
1319 # as the old version. But I think it *should* go here.
1320 return s + ("from line #%s of %s\n" %
1321 (example.lineno, test.name))
1322 elif test.lineno is None:
1323 return s + ("from line #%s of %s in %s\n" %
1324 (example.lineno+1, test.name, test.filename))
1325 else:
1326 lineno = test.lineno+example.lineno+1
1327 return s + ("from line #%s of %s (%s)\n" %
1328 (lineno, test.filename, test.name))
Tim Peters7402f792001-10-02 03:53:41 +00001329
Tim Peters8485b562004-08-04 18:46:34 +00001330 #/////////////////////////////////////////////////////////////////
1331 # DocTest Running
1332 #/////////////////////////////////////////////////////////////////
Tim Peters7402f792001-10-02 03:53:41 +00001333
Tim Peters8485b562004-08-04 18:46:34 +00001334 # A regular expression for handling `want` strings that contain
1335 # expected exceptions. It divides `want` into two pieces: the
1336 # pre-exception output (`out`) and the exception message (`exc`),
1337 # as generated by traceback.format_exception_only(). (I assume
1338 # that the exception_only message is the first non-indented line
1339 # starting with word characters after the "Traceback ...".)
1340 _EXCEPTION_RE = re.compile(('^(?P<out>.*)'
1341 '^(?P<hdr>Traceback \((?:%s|%s)\):)\s*$.*?'
1342 '^(?P<exc>\w+.*)') %
1343 ('most recent call last', 'innermost last'),
1344 re.MULTILINE | re.DOTALL)
Tim Peters7402f792001-10-02 03:53:41 +00001345
Tim Peters8485b562004-08-04 18:46:34 +00001346 _OPTION_DIRECTIVE_RE = re.compile('\s*doctest:\s*(?P<flags>[^#\n]*)')
Tim Peters7402f792001-10-02 03:53:41 +00001347
Tim Peters8485b562004-08-04 18:46:34 +00001348 def __handle_directive(self, example):
1349 """
1350 Check if the given example is actually a directive to doctest
1351 (to turn an optionflag on or off); and if it is, then handle
1352 the directive.
Tim Peters7402f792001-10-02 03:53:41 +00001353
Tim Peters8485b562004-08-04 18:46:34 +00001354 Return true iff the example is actually a directive (and so
1355 should not be executed).
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001356
Tim Peters8a7d2d52001-01-16 07:10:57 +00001357 """
Tim Peters8485b562004-08-04 18:46:34 +00001358 m = self._OPTION_DIRECTIVE_RE.match(example.source)
1359 if m is None:
1360 return False
Tim Peters8a7d2d52001-01-16 07:10:57 +00001361
Tim Peters8485b562004-08-04 18:46:34 +00001362 for flag in m.group('flags').upper().split():
1363 if (flag[:1] not in '+-' or
1364 flag[1:] not in OPTIONFLAGS_BY_NAME):
1365 raise ValueError('Bad doctest option directive: '+flag)
1366 if flag[0] == '+':
1367 self.optionflags |= OPTIONFLAGS_BY_NAME[flag[1:]]
1368 else:
1369 self.optionflags &= ~OPTIONFLAGS_BY_NAME[flag[1:]]
1370 return True
Tim Peters8a7d2d52001-01-16 07:10:57 +00001371
Tim Peters8485b562004-08-04 18:46:34 +00001372 def __run(self, test, compileflags, out):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001373 """
Tim Peters8485b562004-08-04 18:46:34 +00001374 Run the examples in `test`. Write the outcome of each example
1375 with one of the `DocTestRunner.report_*` methods, using the
1376 writer function `out`. `compileflags` is the set of compiler
1377 flags that should be used to execute examples. Return a tuple
1378 `(f, t)`, where `t` is the number of examples tried, and `f`
1379 is the number of examples that failed. The examples are run
1380 in the namespace `test.globs`.
1381 """
1382 # Keep track of the number of failures and tries.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001383 failures = tries = 0
Tim Peters8485b562004-08-04 18:46:34 +00001384
1385 # Save the option flags (since option directives can be used
1386 # to modify them).
1387 original_optionflags = self.optionflags
1388
1389 # Process each example.
1390 for example in test.examples:
1391 # Check if it's an option directive. If it is, then handle
1392 # it, and go on to the next example.
1393 if self.__handle_directive(example):
1394 continue
1395
1396 # Record that we started this example.
1397 tries += 1
1398 self.report_start(out, test, example)
1399
1400 # Run the example in the given context (globs), and record
1401 # any exception that gets raised. (But don't intercept
1402 # keyboard interrupts.)
1403 try:
1404 # If the example is a compound statement on one line,
1405 # like "if 1: print 2", then compile() requires a
1406 # trailing newline. Rather than analyze that, always
1407 # append one (it never hurts).
1408 exec compile(example.source + '\n', "<string>", "single",
1409 compileflags, 1) in test.globs
1410 exception = None
1411 except KeyboardInterrupt:
1412 raise
1413 except:
1414 exception = sys.exc_info()
1415
1416 # Extract the example's actual output from fakeout, and
1417 # write it to `got`. Add a terminating newline if it
1418 # doesn't have already one.
1419 got = self._fakeout.getvalue()
1420 self._fakeout.truncate(0)
1421
1422 # If the example executed without raising any exceptions,
1423 # then verify its output and report its outcome.
1424 if exception is None:
1425 if self.check_output(example.want, got):
1426 self.report_success(out, test, example, got)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001427 else:
Tim Peters8485b562004-08-04 18:46:34 +00001428 self.report_failure(out, test, example, got)
1429 failures += 1
1430
1431 # If the example raised an exception, then check if it was
1432 # expected.
1433 else:
1434 exc_info = sys.exc_info()
1435 exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
1436
1437 # Search the `want` string for an exception. If we don't
1438 # find one, then report an unexpected exception.
1439 m = self._EXCEPTION_RE.match(example.want)
1440 if m is None:
1441 self.report_unexpected_exception(out, test, example,
1442 exc_info)
1443 failures += 1
1444 else:
1445 exc_hdr = m.group('hdr')+'\n' # Exception header
1446 # The test passes iff the pre-exception output and
1447 # the exception description match the values given
1448 # in `want`.
1449 if (self.check_output(m.group('out'), got) and
1450 self.check_output(m.group('exc'), exc_msg)):
1451 # Is +exc_msg the right thing here??
1452 self.report_success(out, test, example,
1453 got+exc_hdr+exc_msg)
1454 else:
1455 self.report_failure(out, test, example,
1456 got+exc_hdr+exc_msg)
1457 failures += 1
1458
1459 # Restore the option flags (in case they were modified)
1460 self.optionflags = original_optionflags
1461
1462 # Record and return the number of failures and tries.
1463 self.__record_outcome(test, failures, tries)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001464 return failures, tries
1465
Tim Peters8485b562004-08-04 18:46:34 +00001466 def __record_outcome(self, test, f, t):
1467 """
1468 Record the fact that the given DocTest (`test`) generated `f`
1469 failures out of `t` tried examples.
1470 """
1471 f2, t2 = self._name2ft.get(test.name, (0,0))
1472 self._name2ft[test.name] = (f+f2, t+t2)
1473 self.failures += f
1474 self.tries += t
1475
1476 def run(self, test, compileflags=None, out=None, clear_globs=True):
1477 """
1478 Run the examples in `test`, and display the results using the
1479 writer function `out`.
1480
1481 The examples are run in the namespace `test.globs`. If
1482 `clear_globs` is true (the default), then this namespace will
1483 be cleared after the test runs, to help with garbage
1484 collection. If you would like to examine the namespace after
1485 the test completes, then use `clear_globs=False`.
1486
1487 `compileflags` gives the set of flags that should be used by
1488 the Python compiler when running the examples. If not
1489 specified, then it will default to the set of future-import
1490 flags that apply to `globs`.
1491
1492 The output of each example is checked using
1493 `DocTestRunner.check_output`, and the results are formatted by
1494 the `DocTestRunner.report_*` methods.
1495 """
1496 if compileflags is None:
1497 compileflags = _extract_future_flags(test.globs)
1498 if out is None:
1499 out = sys.stdout.write
1500 saveout = sys.stdout
1501
1502 try:
1503 sys.stdout = self._fakeout
1504 return self.__run(test, compileflags, out)
1505 finally:
1506 sys.stdout = saveout
Tim Peters8485b562004-08-04 18:46:34 +00001507 if clear_globs:
1508 test.globs.clear()
1509
1510 #/////////////////////////////////////////////////////////////////
1511 # Summarization
1512 #/////////////////////////////////////////////////////////////////
Tim Peters8a7d2d52001-01-16 07:10:57 +00001513 def summarize(self, verbose=None):
1514 """
Tim Peters8485b562004-08-04 18:46:34 +00001515 Print a summary of all the test cases that have been run by
1516 this DocTestRunner, and return a tuple `(f, t)`, where `f` is
1517 the total number of failed examples, and `t` is the total
1518 number of tried examples.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001519
Tim Peters8485b562004-08-04 18:46:34 +00001520 The optional `verbose` argument controls how detailed the
1521 summary is. If the verbosity is not specified, then the
1522 DocTestRunner's verbosity is used.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001523 """
Tim Peters8a7d2d52001-01-16 07:10:57 +00001524 if verbose is None:
Tim Peters8485b562004-08-04 18:46:34 +00001525 verbose = self._verbose
Tim Peters8a7d2d52001-01-16 07:10:57 +00001526 notests = []
1527 passed = []
1528 failed = []
1529 totalt = totalf = 0
Tim Peters8485b562004-08-04 18:46:34 +00001530 for x in self._name2ft.items():
Tim Peters8a7d2d52001-01-16 07:10:57 +00001531 name, (f, t) = x
1532 assert f <= t
Tim Peters8485b562004-08-04 18:46:34 +00001533 totalt += t
1534 totalf += f
Tim Peters8a7d2d52001-01-16 07:10:57 +00001535 if t == 0:
1536 notests.append(name)
1537 elif f == 0:
1538 passed.append( (name, t) )
1539 else:
1540 failed.append(x)
1541 if verbose:
1542 if notests:
1543 print len(notests), "items had no tests:"
1544 notests.sort()
1545 for thing in notests:
1546 print " ", thing
1547 if passed:
1548 print len(passed), "items passed all tests:"
1549 passed.sort()
1550 for thing, count in passed:
1551 print " %3d tests in %s" % (count, thing)
1552 if failed:
Tim Peters8485b562004-08-04 18:46:34 +00001553 print self.DIVIDER
Tim Peters8a7d2d52001-01-16 07:10:57 +00001554 print len(failed), "items had failures:"
1555 failed.sort()
1556 for thing, (f, t) in failed:
1557 print " %3d of %3d in %s" % (f, t, thing)
1558 if verbose:
Tim Peters8485b562004-08-04 18:46:34 +00001559 print totalt, "tests in", len(self._name2ft), "items."
Tim Peters8a7d2d52001-01-16 07:10:57 +00001560 print totalt - totalf, "passed and", totalf, "failed."
1561 if totalf:
1562 print "***Test Failed***", totalf, "failures."
1563 elif verbose:
1564 print "Test passed."
1565 return totalf, totalt
1566
Tim Peters19397e52004-08-06 22:02:59 +00001567class DocTestFailure(Exception):
1568 """A DocTest example has failed in debugging mode.
1569
1570 The exception instance has variables:
1571
1572 - test: the DocTest object being run
1573
1574 - excample: the Example object that failed
1575
1576 - got: the actual output
1577 """
1578 def __init__(self, test, example, got):
1579 self.test = test
1580 self.example = example
1581 self.got = got
1582
1583 def __str__(self):
1584 return str(self.test)
1585
1586class UnexpectedException(Exception):
1587 """A DocTest example has encountered an unexpected exception
1588
1589 The exception instance has variables:
1590
1591 - test: the DocTest object being run
1592
1593 - excample: the Example object that failed
1594
1595 - exc_info: the exception info
1596 """
1597 def __init__(self, test, example, exc_info):
1598 self.test = test
1599 self.example = example
1600 self.exc_info = exc_info
1601
1602 def __str__(self):
1603 return str(self.test)
1604
1605class DebugRunner(DocTestRunner):
1606 r"""Run doc tests but raise an exception as soon as there is a failure.
1607
1608 If an unexpected exception occurs, an UnexpectedException is raised.
1609 It contains the test, the example, and the original exception:
1610
1611 >>> runner = DebugRunner(verbose=False)
1612 >>> test = DocTest('>>> raise KeyError\n42', {}, 'foo', 'foo.py', 0)
1613 >>> try:
1614 ... runner.run(test)
1615 ... except UnexpectedException, failure:
1616 ... pass
1617
1618 >>> failure.test is test
1619 True
1620
1621 >>> failure.example.want
1622 '42\n'
1623
1624 >>> exc_info = failure.exc_info
1625 >>> raise exc_info[0], exc_info[1], exc_info[2]
1626 Traceback (most recent call last):
1627 ...
1628 KeyError
1629
1630 We wrap the original exception to give the calling application
1631 access to the test and example information.
1632
1633 If the output doesn't match, then a DocTestFailure is raised:
1634
1635 >>> test = DocTest('''
1636 ... >>> x = 1
1637 ... >>> x
1638 ... 2
1639 ... ''', {}, 'foo', 'foo.py', 0)
1640
1641 >>> try:
1642 ... runner.run(test)
1643 ... except DocTestFailure, failure:
1644 ... pass
1645
1646 DocTestFailure objects provide access to the test:
1647
1648 >>> failure.test is test
1649 True
1650
1651 As well as to the example:
1652
1653 >>> failure.example.want
1654 '2\n'
1655
1656 and the actual output:
1657
1658 >>> failure.got
1659 '1\n'
1660
1661 If a failure or error occurs, the globals are left intact:
1662
1663 >>> del test.globs['__builtins__']
1664 >>> test.globs
1665 {'x': 1}
1666
1667 >>> test = DocTest('''
1668 ... >>> x = 2
1669 ... >>> raise KeyError
1670 ... ''', {}, 'foo', 'foo.py', 0)
1671
1672 >>> runner.run(test)
1673 Traceback (most recent call last):
1674 ...
1675 UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
1676
1677 >>> del test.globs['__builtins__']
1678 >>> test.globs
1679 {'x': 2}
1680
1681 But the globals are cleared if there is no error:
1682
1683 >>> test = DocTest('''
1684 ... >>> x = 2
1685 ... ''', {}, 'foo', 'foo.py', 0)
1686
1687 >>> runner.run(test)
1688 (0, 1)
1689
1690 >>> test.globs
1691 {}
1692
1693 """
1694
1695 def run(self, test, compileflags=None, out=None, clear_globs=True):
1696 r = DocTestRunner.run(self, test, compileflags, out, False)
1697 if clear_globs:
1698 test.globs.clear()
1699 return r
1700
1701 def report_unexpected_exception(self, out, test, example, exc_info):
1702 raise UnexpectedException(test, example, exc_info)
1703
1704 def report_failure(self, out, test, example, got):
1705 raise DocTestFailure(test, example, got)
1706
Tim Peters8485b562004-08-04 18:46:34 +00001707######################################################################
1708## 5. Test Functions
1709######################################################################
1710# These should be backwards compatible.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001711
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001712def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters19397e52004-08-06 22:02:59 +00001713 report=True, optionflags=0, extraglobs=None,
1714 raise_on_error=False):
Tim Peters6ebe61f2003-06-27 20:48:05 +00001715 """m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters8485b562004-08-04 18:46:34 +00001716 report=True, optionflags=0, extraglobs=None
Tim Peters8a7d2d52001-01-16 07:10:57 +00001717
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001718 Test examples in docstrings in functions and classes reachable
1719 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001720 with m.__doc__. Unless isprivate is specified, private names
1721 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001722
1723 Also test examples reachable from dict m.__test__ if it exists and is
1724 not None. m.__dict__ maps names to functions, classes and strings;
1725 function and class docstrings are tested even if the name is private;
1726 strings are tested directly, as if they were docstrings.
1727
1728 Return (#failures, #tests).
1729
1730 See doctest.__doc__ for an overview.
1731
1732 Optional keyword arg "name" gives the name of the module; by default
1733 use m.__name__.
1734
1735 Optional keyword arg "globs" gives a dict to be used as the globals
1736 when executing examples; by default, use m.__dict__. A copy of this
1737 dict is actually used for each docstring, so that each docstring's
1738 examples start with a clean slate.
1739
Tim Peters8485b562004-08-04 18:46:34 +00001740 Optional keyword arg "extraglobs" gives a dictionary that should be
1741 merged into the globals that are used to execute examples. By
1742 default, no extra globals are used. This is new in 2.4.
1743
Tim Peters8a7d2d52001-01-16 07:10:57 +00001744 Optional keyword arg "verbose" prints lots of stuff if true, prints
1745 only failures if false; by default, it's true iff "-v" is in sys.argv.
1746
1747 Optional keyword arg "isprivate" specifies a function used to
1748 determine whether a name is private. The default function is
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001749 treat all functions as public. Optionally, "isprivate" can be
1750 set to doctest.is_private to skip over functions marked as private
1751 using the underscore naming convention; see its docs for details.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001752
1753 Optional keyword arg "report" prints a summary at the end when true,
1754 else prints nothing at the end. In verbose mode, the summary is
1755 detailed, else very brief (in fact, empty if all tests passed).
1756
Tim Peters6ebe61f2003-06-27 20:48:05 +00001757 Optional keyword arg "optionflags" or's together module constants,
1758 and defaults to 0. This is new in 2.3. Possible values:
1759
1760 DONT_ACCEPT_TRUE_FOR_1
1761 By default, if an expected output block contains just "1",
1762 an actual output block containing just "True" is considered
1763 to be a match, and similarly for "0" versus "False". When
1764 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1765 is allowed.
1766
Tim Peters8485b562004-08-04 18:46:34 +00001767 DONT_ACCEPT_BLANKLINE
1768 By default, if an expected output block contains a line
1769 containing only the string "<BLANKLINE>", then that line
1770 will match a blank line in the actual output. When
1771 DONT_ACCEPT_BLANKLINE is specified, this substitution is
1772 not allowed.
1773
1774 NORMALIZE_WHITESPACE
1775 When NORMALIZE_WHITESPACE is specified, all sequences of
1776 whitespace are treated as equal. I.e., any sequence of
1777 whitespace within the expected output will match any
1778 sequence of whitespace within the actual output.
1779
1780 ELLIPSIS
1781 When ELLIPSIS is specified, then an ellipsis marker
1782 ("...") in the expected output can match any substring in
1783 the actual output.
1784
1785 UNIFIED_DIFF
1786 When UNIFIED_DIFF is specified, failures that involve
1787 multi-line expected and actual outputs will be displayed
1788 using a unified diff.
1789
1790 CONTEXT_DIFF
1791 When CONTEXT_DIFF is specified, failures that involve
1792 multi-line expected and actual outputs will be displayed
1793 using a context diff.
Tim Peters19397e52004-08-06 22:02:59 +00001794
1795 Optional keyword arg "raise_on_error" raises an exception on the
1796 first unexpected exception or failure. This allows failures to be
1797 post-mortem debugged.
1798
Tim Peters8485b562004-08-04 18:46:34 +00001799 """
1800
1801 """ [XX] This is no longer true:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001802 Advanced tomfoolery: testmod runs methods of a local instance of
1803 class doctest.Tester, then merges the results into (or creates)
1804 global Tester instance doctest.master. Methods of doctest.master
1805 can be called directly too, if you want to do something unusual.
1806 Passing report=0 to testmod is especially useful then, to delay
1807 displaying a summary. Invoke doctest.master.summarize(verbose)
1808 when you're done fiddling.
1809 """
Tim Peters8485b562004-08-04 18:46:34 +00001810 # If no module was given, then use __main__.
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001811 if m is None:
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001812 # DWA - m will still be None if this wasn't invoked from the command
1813 # line, in which case the following TypeError is about as good an error
1814 # as we should expect
1815 m = sys.modules.get('__main__')
1816
Tim Peters8485b562004-08-04 18:46:34 +00001817 # Check that we were actually given a module.
1818 if not inspect.ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001819 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8485b562004-08-04 18:46:34 +00001820
1821 # If no name was given, then use the module's name.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001822 if name is None:
1823 name = m.__name__
Tim Peters8485b562004-08-04 18:46:34 +00001824
1825 # Find, parse, and run all tests in the given module.
1826 finder = DocTestFinder(namefilter=isprivate)
Tim Peters19397e52004-08-06 22:02:59 +00001827
1828 if raise_on_error:
1829 runner = DebugRunner(verbose=verbose, optionflags=optionflags)
1830 else:
1831 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1832
Tim Peters8485b562004-08-04 18:46:34 +00001833 for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
1834 runner.run(test)
1835
Tim Peters8a7d2d52001-01-16 07:10:57 +00001836 if report:
Tim Peters8485b562004-08-04 18:46:34 +00001837 runner.summarize()
Tim Peters8a7d2d52001-01-16 07:10:57 +00001838
Tim Peters8485b562004-08-04 18:46:34 +00001839 return runner.failures, runner.tries
Tim Petersdb3756d2003-06-29 05:30:48 +00001840
Tim Peters8485b562004-08-04 18:46:34 +00001841def run_docstring_examples(f, globs, verbose=False, name="NoName",
1842 compileflags=None, optionflags=0):
1843 """
1844 Test examples in the given object's docstring (`f`), using `globs`
1845 as globals. Optional argument `name` is used in failure messages.
1846 If the optional argument `verbose` is true, then generate output
1847 even if there are no failures.
Tim Petersdb3756d2003-06-29 05:30:48 +00001848
Tim Peters8485b562004-08-04 18:46:34 +00001849 `compileflags` gives the set of flags that should be used by the
1850 Python compiler when running the examples. If not specified, then
1851 it will default to the set of future-import flags that apply to
1852 `globs`.
Tim Petersdb3756d2003-06-29 05:30:48 +00001853
Tim Peters8485b562004-08-04 18:46:34 +00001854 Optional keyword arg `optionflags` specifies options for the
1855 testing and output. See the documentation for `testmod` for more
1856 information.
1857 """
1858 # Find, parse, and run all tests in the given module.
1859 finder = DocTestFinder(verbose=verbose, recurse=False)
1860 runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
1861 for test in finder.find(f, name, globs=globs):
1862 runner.run(test, compileflags=compileflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001863
Tim Peters8485b562004-08-04 18:46:34 +00001864######################################################################
1865## 6. Tester
1866######################################################################
1867# This is provided only for backwards compatibility. It's not
1868# actually used in any way.
Tim Petersdb3756d2003-06-29 05:30:48 +00001869
Tim Peters8485b562004-08-04 18:46:34 +00001870class Tester:
1871 def __init__(self, mod=None, globs=None, verbose=None,
1872 isprivate=None, optionflags=0):
1873 if mod is None and globs is None:
1874 raise TypeError("Tester.__init__: must specify mod or globs")
1875 if mod is not None and not _ismodule(mod):
1876 raise TypeError("Tester.__init__: mod must be a module; %r" %
1877 (mod,))
1878 if globs is None:
1879 globs = mod.__dict__
1880 self.globs = globs
Tim Petersdb3756d2003-06-29 05:30:48 +00001881
Tim Peters8485b562004-08-04 18:46:34 +00001882 self.verbose = verbose
1883 self.isprivate = isprivate
1884 self.optionflags = optionflags
1885 self.testfinder = DocTestFinder(namefilter=isprivate)
1886 self.testrunner = DocTestRunner(verbose=verbose,
1887 optionflags=optionflags)
Tim Petersdb3756d2003-06-29 05:30:48 +00001888
Tim Peters8485b562004-08-04 18:46:34 +00001889 def runstring(self, s, name):
1890 test = DocTest(s, self.globs, name, None, None)
1891 if self.verbose:
1892 print "Running string", name
1893 (f,t) = self.testrunner.run(test)
1894 if self.verbose:
1895 print f, "of", t, "examples failed in string", name
1896 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001897
Tim Peters8485b562004-08-04 18:46:34 +00001898 def rundoc(self, object, name=None, module=None, ignore_imports=True):
1899 f = t = 0
1900 tests = self.testfinder.find(object, name, module=module,
1901 globs=self.globs,
1902 ignore_imports=ignore_imports)
1903 for test in tests:
1904 (f2, t2) = self.testrunner.run(test)
1905 (f,t) = (f+f2, t+t2)
1906 return (f,t)
Tim Petersdb3756d2003-06-29 05:30:48 +00001907
Tim Peters8485b562004-08-04 18:46:34 +00001908 def rundict(self, d, name, module=None):
1909 import new
1910 m = new.module(name)
1911 m.__dict__.update(d)
1912 ignore_imports = (module is not None)
1913 return self.rundoc(m, name, module, ignore_imports)
Tim Petersdb3756d2003-06-29 05:30:48 +00001914
Tim Peters8485b562004-08-04 18:46:34 +00001915 def run__test__(self, d, name):
1916 import new
1917 m = new.module(name)
1918 m.__test__ = d
1919 return self.rundoc(m, name, module)
Tim Petersdb3756d2003-06-29 05:30:48 +00001920
Tim Peters8485b562004-08-04 18:46:34 +00001921 def summarize(self, verbose=None):
1922 return self.testrunner.summarize(verbose)
Tim Petersdb3756d2003-06-29 05:30:48 +00001923
Tim Peters8485b562004-08-04 18:46:34 +00001924 def merge(self, other):
1925 d = self.testrunner._name2ft
1926 for name, (f, t) in other.testrunner._name2ft.items():
1927 if name in d:
1928 print "*** Tester.merge: '" + name + "' in both" \
1929 " testers; summing outcomes."
1930 f2, t2 = d[name]
1931 f = f + f2
1932 t = t + t2
1933 d[name] = f, t
Tim Petersdb3756d2003-06-29 05:30:48 +00001934
Tim Peters8485b562004-08-04 18:46:34 +00001935######################################################################
1936## 7. Unittest Support
1937######################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001938
Tim Peters19397e52004-08-06 22:02:59 +00001939class DocTestCase(unittest.TestCase):
Tim Petersdb3756d2003-06-29 05:30:48 +00001940
Tim Peters19397e52004-08-06 22:02:59 +00001941 def __init__(self, test, optionflags=0, setUp=None, tearDown=None):
Jim Fultona643b652004-07-14 19:06:50 +00001942 unittest.TestCase.__init__(self)
Tim Peters19397e52004-08-06 22:02:59 +00001943 self._dt_optionflags = optionflags
1944 self._dt_test = test
1945 self._dt_setUp = setUp
1946 self._dt_tearDown = tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00001947
Jim Fultona643b652004-07-14 19:06:50 +00001948 def setUp(self):
Tim Peters19397e52004-08-06 22:02:59 +00001949 if self._dt_setUp is not None:
1950 self._dt_setUp()
Jim Fultona643b652004-07-14 19:06:50 +00001951
1952 def tearDown(self):
Tim Peters19397e52004-08-06 22:02:59 +00001953 if self._dt_tearDown is not None:
1954 self._dt_tearDown()
Jim Fultona643b652004-07-14 19:06:50 +00001955
1956 def runTest(self):
Tim Peters19397e52004-08-06 22:02:59 +00001957 test = self._dt_test
Jim Fultona643b652004-07-14 19:06:50 +00001958 old = sys.stdout
1959 new = StringIO()
Tim Peters19397e52004-08-06 22:02:59 +00001960 runner = DocTestRunner(optionflags=self._dt_optionflags, verbose=False)
1961
Jim Fultona643b652004-07-14 19:06:50 +00001962 try:
Tim Peters19397e52004-08-06 22:02:59 +00001963 runner.DIVIDER = "-"*70
1964 failures, tries = runner.run(test, out=new.write)
Jim Fultona643b652004-07-14 19:06:50 +00001965 finally:
1966 sys.stdout = old
1967
1968 if failures:
Tim Peters19397e52004-08-06 22:02:59 +00001969 raise self.failureException(self.format_failure(new.getvalue()))
Tim Peters8485b562004-08-04 18:46:34 +00001970
Tim Peters19397e52004-08-06 22:02:59 +00001971 def format_failure(self, err):
1972 test = self._dt_test
1973 if test.lineno is None:
1974 lineno = 'unknown line number'
1975 else:
1976 lineno = 'line %s' % test.lineno
1977 lname = '.'.join(test.name.split('.')[-1:])
1978 return ('Failed doctest test for %s\n'
1979 ' File "%s", line %s, in %s\n\n%s'
1980 % (test.name, test.filename, lineno, lname, err)
1981 )
1982
1983 def debug(self):
1984 r"""Run the test case without results and without catching exceptions
1985
1986 The unit test framework includes a debug method on test cases
1987 and test suites to support post-mortem debugging. The test code
1988 is run in such a way that errors are not caught. This way a
1989 caller can catch the errors and initiate post-mortem debugging.
1990
1991 The DocTestCase provides a debug method that raises
1992 UnexpectedException errors if there is an unexepcted
1993 exception:
1994
1995 >>> test = DocTest('>>> raise KeyError\n42',
1996 ... {}, 'foo', 'foo.py', 0)
1997 >>> case = DocTestCase(test)
1998 >>> try:
1999 ... case.debug()
2000 ... except UnexpectedException, failure:
2001 ... pass
2002
2003 The UnexpectedException contains the test, the example, and
2004 the original exception:
2005
2006 >>> failure.test is test
2007 True
2008
2009 >>> failure.example.want
2010 '42\n'
2011
2012 >>> exc_info = failure.exc_info
2013 >>> raise exc_info[0], exc_info[1], exc_info[2]
2014 Traceback (most recent call last):
2015 ...
2016 KeyError
2017
2018 If the output doesn't match, then a DocTestFailure is raised:
2019
2020 >>> test = DocTest('''
2021 ... >>> x = 1
2022 ... >>> x
2023 ... 2
2024 ... ''', {}, 'foo', 'foo.py', 0)
2025 >>> case = DocTestCase(test)
2026
2027 >>> try:
2028 ... case.debug()
2029 ... except DocTestFailure, failure:
2030 ... pass
2031
2032 DocTestFailure objects provide access to the test:
2033
2034 >>> failure.test is test
2035 True
2036
2037 As well as to the example:
2038
2039 >>> failure.example.want
2040 '2\n'
2041
2042 and the actual output:
2043
2044 >>> failure.got
2045 '1\n'
2046
2047 """
2048
2049 runner = DebugRunner(verbose = False, optionflags=self._dt_optionflags)
2050 runner.run(self._dt_test, out=nooutput)
Jim Fultona643b652004-07-14 19:06:50 +00002051
2052 def id(self):
Tim Peters19397e52004-08-06 22:02:59 +00002053 return self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002054
2055 def __repr__(self):
Tim Peters19397e52004-08-06 22:02:59 +00002056 name = self._dt_test.name.split('.')
Jim Fultona643b652004-07-14 19:06:50 +00002057 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
2058
2059 __str__ = __repr__
2060
2061 def shortDescription(self):
Tim Peters19397e52004-08-06 22:02:59 +00002062 return "Doctest: " + self._dt_test.name
Jim Fultona643b652004-07-14 19:06:50 +00002063
Tim Peters19397e52004-08-06 22:02:59 +00002064def nooutput(*args):
2065 pass
Jim Fultona643b652004-07-14 19:06:50 +00002066
Tim Peters19397e52004-08-06 22:02:59 +00002067def DocTestSuite(module=None, globs=None, extraglobs=None,
2068 optionflags=0, test_finder=None,
Tim Peters8485b562004-08-04 18:46:34 +00002069 setUp=lambda: None, tearDown=lambda: None):
2070 """
Tim Peters19397e52004-08-06 22:02:59 +00002071 Convert doctest tests for a mudule to a unittest test suite.
Jim Fultona643b652004-07-14 19:06:50 +00002072
Tim Peters19397e52004-08-06 22:02:59 +00002073 This converts each documentation string in a module that
2074 contains doctest tests to a unittest test case. If any of the
2075 tests in a doc string fail, then the test case fails. An exception
2076 is raised showing the name of the file containing the test and a
Jim Fultona643b652004-07-14 19:06:50 +00002077 (sometimes approximate) line number.
2078
Tim Peters19397e52004-08-06 22:02:59 +00002079 The `module` argument provides the module to be tested. The argument
Jim Fultona643b652004-07-14 19:06:50 +00002080 can be either a module or a module name.
2081
2082 If no argument is given, the calling module is used.
Jim Fultona643b652004-07-14 19:06:50 +00002083 """
Jim Fultona643b652004-07-14 19:06:50 +00002084
Tim Peters8485b562004-08-04 18:46:34 +00002085 if test_finder is None:
2086 test_finder = DocTestFinder()
Tim Peters8485b562004-08-04 18:46:34 +00002087
Tim Peters19397e52004-08-06 22:02:59 +00002088 module = _normalize_module(module)
2089 tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
2090 if globs is None:
2091 globs = module.__dict__
2092 if not tests: # [XX] why do we want to do this?
2093 raise ValueError(module, "has no tests")
Tim Petersdb3756d2003-06-29 05:30:48 +00002094
2095 tests.sort()
2096 suite = unittest.TestSuite()
Tim Peters8485b562004-08-04 18:46:34 +00002097 for test in tests:
Tim Peters19397e52004-08-06 22:02:59 +00002098 if len(test.examples) == 0:
2099 continue
Tim Peters8485b562004-08-04 18:46:34 +00002100 if not test.filename:
Tim Petersdb3756d2003-06-29 05:30:48 +00002101 filename = module.__file__
2102 if filename.endswith(".pyc"):
2103 filename = filename[:-1]
2104 elif filename.endswith(".pyo"):
2105 filename = filename[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002106 test.filename = filename
Tim Peters19397e52004-08-06 22:02:59 +00002107 suite.addTest(DocTestCase(test, optionflags, setUp, tearDown))
2108
2109 return suite
2110
2111class DocFileCase(DocTestCase):
2112
2113 def id(self):
2114 return '_'.join(self._dt_test.name.split('.'))
2115
2116 def __repr__(self):
2117 return self._dt_test.filename
2118 __str__ = __repr__
2119
2120 def format_failure(self, err):
2121 return ('Failed doctest test for %s\n File "%s", line 0\n\n%s'
2122 % (self._dt_test.name, self._dt_test.filename, err)
2123 )
2124
2125def DocFileTest(path, package=None, globs=None,
2126 setUp=None, tearDown=None,
2127 optionflags=0):
2128 package = _normalize_module(package)
2129 name = path.split('/')[-1]
2130 dir = os.path.split(package.__file__)[0]
2131 path = os.path.join(dir, *(path.split('/')))
2132 doc = open(path).read()
2133
2134 if globs is None:
2135 globs = {}
2136
2137 test = DocTest(doc, globs, name, path, 0)
2138
2139 return DocFileCase(test, optionflags, setUp, tearDown)
2140
2141def DocFileSuite(*paths, **kw):
2142 """Creates a suite of doctest files.
2143
2144 One or more text file paths are given as strings. These should
2145 use "/" characters to separate path segments. Paths are relative
2146 to the directory of the calling module, or relative to the package
2147 passed as a keyword argument.
2148
2149 A number of options may be provided as keyword arguments:
2150
2151 package
2152 The name of a Python package. Text-file paths will be
2153 interpreted relative to the directory containing this package.
2154 The package may be supplied as a package object or as a dotted
2155 package name.
2156
2157 setUp
2158 The name of a set-up function. This is called before running the
2159 tests in each file.
2160
2161 tearDown
2162 The name of a tear-down function. This is called after running the
2163 tests in each file.
2164
2165 globs
2166 A dictionary containing initial global variables for the tests.
2167 """
2168 suite = unittest.TestSuite()
2169
2170 # We do this here so that _normalize_module is called at the right
2171 # level. If it were called in DocFileTest, then this function
2172 # would be the caller and we might guess the package incorrectly.
2173 kw['package'] = _normalize_module(kw.get('package'))
2174
2175 for path in paths:
2176 suite.addTest(DocFileTest(path, **kw))
Jim Fultona643b652004-07-14 19:06:50 +00002177
Tim Petersdb3756d2003-06-29 05:30:48 +00002178 return suite
2179
Tim Peters8485b562004-08-04 18:46:34 +00002180######################################################################
2181## 8. Debugging Support
2182######################################################################
Jim Fultona643b652004-07-14 19:06:50 +00002183
Tim Peters19397e52004-08-06 22:02:59 +00002184def script_from_examples(s):
2185 r"""Extract script from text with examples.
2186
2187 Converts text with examples to a Python script. Example input is
2188 converted to regular code. Example output and all other words
2189 are converted to comments:
2190
2191 >>> text = '''
2192 ... Here are examples of simple math.
2193 ...
2194 ... Python has super accurate integer addition
2195 ...
2196 ... >>> 2 + 2
2197 ... 5
2198 ...
2199 ... And very friendly error messages:
2200 ...
2201 ... >>> 1/0
2202 ... To Infinity
2203 ... And
2204 ... Beyond
2205 ...
2206 ... You can use logic if you want:
2207 ...
2208 ... >>> if 0:
2209 ... ... blah
2210 ... ... blah
2211 ... ...
2212 ...
2213 ... Ho hum
2214 ... '''
2215
2216 >>> print script_from_examples(text)
2217 # Here are examples of simple math.
2218 #
2219 # Python has super accurate integer addition
2220 #
2221 2 + 2
2222 # Expected:
2223 # 5
2224 #
2225 # And very friendly error messages:
2226 #
2227 1/0
2228 # Expected:
2229 # To Infinity
2230 # And
2231 # Beyond
2232 #
2233 # You can use logic if you want:
2234 #
2235 if 0:
2236 blah
2237 blah
2238 <BLANKLINE>
2239 #
2240 # Ho hum
2241 """
2242
2243 return Parser('<string>', s).get_program()
2244
Tim Peters8485b562004-08-04 18:46:34 +00002245def _want_comment(example):
2246 """
Tim Peters19397e52004-08-06 22:02:59 +00002247 Return a comment containing the expected output for the given example.
Tim Peters8485b562004-08-04 18:46:34 +00002248 """
Jim Fultona643b652004-07-14 19:06:50 +00002249 # Return the expected output, if any
Tim Peters8485b562004-08-04 18:46:34 +00002250 want = example.want
2251 if want:
Tim Peters19397e52004-08-06 22:02:59 +00002252 if want[-1] == '\n':
2253 want = want[:-1]
Tim Peters8485b562004-08-04 18:46:34 +00002254 want = "\n# ".join(want.split("\n"))
2255 want = "\n# Expected:\n# %s" % want
2256 return want
Tim Petersdb3756d2003-06-29 05:30:48 +00002257
2258def testsource(module, name):
Tim Peters19397e52004-08-06 22:02:59 +00002259 """Extract the test sources from a doctest docstring as a script.
Tim Petersdb3756d2003-06-29 05:30:48 +00002260
2261 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00002262 test to be debugged and the name (within the module) of the object
2263 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00002264 """
Tim Peters8485b562004-08-04 18:46:34 +00002265 module = _normalize_module(module)
2266 tests = DocTestFinder().find(module)
2267 test = [t for t in tests if t.name == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00002268 if not test:
2269 raise ValueError(name, "not found in tests")
2270 test = test[0]
Tim Peters19397e52004-08-06 22:02:59 +00002271 testsrc = script_from_examples(test.docstring)
Jim Fultona643b652004-07-14 19:06:50 +00002272 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00002273
Jim Fultona643b652004-07-14 19:06:50 +00002274def debug_src(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002275 """Debug a single doctest docstring, in argument `src`'"""
2276 testsrc = script_from_examples(src)
Tim Peters8485b562004-08-04 18:46:34 +00002277 debug_script(testsrc, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002278
Jim Fultona643b652004-07-14 19:06:50 +00002279def debug_script(src, pm=False, globs=None):
Tim Peters19397e52004-08-06 22:02:59 +00002280 "Debug a test script. `src` is the script, as a string."
Tim Petersdb3756d2003-06-29 05:30:48 +00002281 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00002282
Tim Petersdb3756d2003-06-29 05:30:48 +00002283 srcfilename = tempfile.mktemp("doctestdebug.py")
Tim Peters8485b562004-08-04 18:46:34 +00002284 f = open(srcfilename, 'w')
2285 f.write(src)
2286 f.close()
2287
Jim Fultona643b652004-07-14 19:06:50 +00002288 if globs:
2289 globs = globs.copy()
2290 else:
2291 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00002292
Tim Peters8485b562004-08-04 18:46:34 +00002293 if pm:
2294 try:
2295 execfile(srcfilename, globs, globs)
2296 except:
2297 print sys.exc_info()[1]
2298 pdb.post_mortem(sys.exc_info()[2])
2299 else:
2300 # Note that %r is vital here. '%s' instead can, e.g., cause
2301 # backslashes to get treated as metacharacters on Windows.
2302 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00002303
Jim Fultona643b652004-07-14 19:06:50 +00002304def debug(module, name, pm=False):
Tim Peters19397e52004-08-06 22:02:59 +00002305 """Debug a single doctest docstring.
Jim Fultona643b652004-07-14 19:06:50 +00002306
2307 Provide the module (or dotted name of the module) containing the
2308 test to be debugged and the name (within the module) of the object
Tim Peters19397e52004-08-06 22:02:59 +00002309 with the docstring with tests to be debugged.
Jim Fultona643b652004-07-14 19:06:50 +00002310 """
Tim Peters8485b562004-08-04 18:46:34 +00002311 module = _normalize_module(module)
Jim Fultona643b652004-07-14 19:06:50 +00002312 testsrc = testsource(module, name)
2313 debug_script(testsrc, pm, module.__dict__)
2314
Tim Peters8485b562004-08-04 18:46:34 +00002315######################################################################
2316## 9. Example Usage
2317######################################################################
Tim Peters8a7d2d52001-01-16 07:10:57 +00002318class _TestClass:
2319 """
2320 A pointless class, for sanity-checking of docstring testing.
2321
2322 Methods:
2323 square()
2324 get()
2325
2326 >>> _TestClass(13).get() + _TestClass(-12).get()
2327 1
2328 >>> hex(_TestClass(13).square().get())
2329 '0xa9'
2330 """
2331
2332 def __init__(self, val):
2333 """val -> _TestClass object with associated value val.
2334
2335 >>> t = _TestClass(123)
2336 >>> print t.get()
2337 123
2338 """
2339
2340 self.val = val
2341
2342 def square(self):
2343 """square() -> square TestClass's associated value
2344
2345 >>> _TestClass(13).square().get()
2346 169
2347 """
2348
2349 self.val = self.val ** 2
2350 return self
2351
2352 def get(self):
2353 """get() -> return TestClass's associated value.
2354
2355 >>> x = _TestClass(-42)
2356 >>> print x.get()
2357 -42
2358 """
2359
2360 return self.val
2361
2362__test__ = {"_TestClass": _TestClass,
2363 "string": r"""
2364 Example of a string object, searched as-is.
2365 >>> x = 1; y = 2
2366 >>> x + y, x * y
2367 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00002368 """,
2369 "bool-int equivalence": r"""
2370 In 2.2, boolean expressions displayed
2371 0 or 1. By default, we still accept
2372 them. This can be disabled by passing
2373 DONT_ACCEPT_TRUE_FOR_1 to the new
2374 optionflags argument.
2375 >>> 4 == 4
2376 1
2377 >>> 4 == 4
2378 True
2379 >>> 4 > 4
2380 0
2381 >>> 4 > 4
2382 False
2383 """,
Tim Peters8485b562004-08-04 18:46:34 +00002384 "blank lines": r"""
2385 Blank lines can be marked with <BLANKLINE>:
2386 >>> print 'foo\n\nbar\n'
2387 foo
2388 <BLANKLINE>
2389 bar
2390 <BLANKLINE>
2391 """,
2392 }
2393# "ellipsis": r"""
2394# If the ellipsis flag is used, then '...' can be used to
2395# elide substrings in the desired output:
2396# >>> print range(1000)
2397# [0, 1, 2, ..., 999]
2398# """,
2399# "whitespace normalization": r"""
2400# If the whitespace normalization flag is used, then
2401# differences in whitespace are ignored.
2402# >>> print range(30)
2403# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
2404# 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
2405# 27, 28, 29]
2406# """,
2407# }
2408
2409def test1(): r"""
2410>>> from doctest import Tester
2411>>> t = Tester(globs={'x': 42}, verbose=0)
2412>>> t.runstring(r'''
2413... >>> x = x * 2
2414... >>> print x
2415... 42
2416... ''', 'XYZ')
2417**********************************************************************
2418Failure in example: print x
2419from line #2 of XYZ
2420Expected: 42
2421Got: 84
2422(1, 2)
2423>>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
2424(0, 2)
2425>>> t.summarize()
2426**********************************************************************
24271 items had failures:
2428 1 of 2 in XYZ
2429***Test Failed*** 1 failures.
2430(1, 4)
2431>>> t.summarize(verbose=1)
24321 items passed all tests:
2433 2 tests in example2
2434**********************************************************************
24351 items had failures:
2436 1 of 2 in XYZ
24374 tests in 2 items.
24383 passed and 1 failed.
2439***Test Failed*** 1 failures.
2440(1, 4)
2441"""
2442
2443def test2(): r"""
2444 >>> t = Tester(globs={}, verbose=1)
2445 >>> test = r'''
2446 ... # just an example
2447 ... >>> x = 1 + 2
2448 ... >>> x
2449 ... 3
2450 ... '''
2451 >>> t.runstring(test, "Example")
2452 Running string Example
2453 Trying: x = 1 + 2
2454 Expecting: nothing
2455 ok
2456 Trying: x
2457 Expecting: 3
2458 ok
2459 0 of 2 examples failed in string Example
2460 (0, 2)
2461"""
2462def test3(): r"""
2463 >>> t = Tester(globs={}, verbose=0)
2464 >>> def _f():
2465 ... '''Trivial docstring example.
2466 ... >>> assert 2 == 2
2467 ... '''
2468 ... return 32
2469 ...
2470 >>> t.rundoc(_f) # expect 0 failures in 1 example
2471 (0, 1)
2472"""
2473def test4(): """
2474 >>> import new
2475 >>> m1 = new.module('_m1')
2476 >>> m2 = new.module('_m2')
2477 >>> test_data = \"""
2478 ... def _f():
2479 ... '''>>> assert 1 == 1
2480 ... '''
2481 ... def g():
2482 ... '''>>> assert 2 != 1
2483 ... '''
2484 ... class H:
2485 ... '''>>> assert 2 > 1
2486 ... '''
2487 ... def bar(self):
2488 ... '''>>> assert 1 < 2
2489 ... '''
2490 ... \"""
2491 >>> exec test_data in m1.__dict__
2492 >>> exec test_data in m2.__dict__
2493 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
2494
2495 Tests that objects outside m1 are excluded:
2496
2497 >>> t = Tester(globs={}, verbose=0, isprivate=is_private)
2498 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
2499 (0, 3)
2500
2501 Again, but with the default isprivate function allowing _f:
2502
2503 >>> t = Tester(globs={}, verbose=0)
2504 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
2505 (0, 4)
2506
2507 And once more, not excluding stuff outside m1:
2508
2509 >>> t = Tester(globs={}, verbose=0)
2510 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
2511 (0, 8)
2512
2513 The exclusion of objects from outside the designated module is
2514 meant to be invoked automagically by testmod.
2515
2516 >>> testmod(m1, isprivate=is_private, verbose=False)
2517 (0, 3)
2518"""
Tim Peters8a7d2d52001-01-16 07:10:57 +00002519
2520def _test():
Tim Peters8485b562004-08-04 18:46:34 +00002521 #import doctest
2522 #doctest.testmod(doctest, verbose=False,
2523 # optionflags=ELLIPSIS | NORMALIZE_WHITESPACE |
2524 # UNIFIED_DIFF)
2525 #print '~'*70
2526 r = unittest.TextTestRunner()
2527 r.run(DocTestSuite())
Tim Peters8a7d2d52001-01-16 07:10:57 +00002528
2529if __name__ == "__main__":
2530 _test()