Files for 2.1b1 distribution.
[python/dscho.git] / Lib / doctest.py
blob9c0ecc87a8b511a9dfc545c2cd4a42afb09b4987
1 # Module doctest version 0.9.7
2 # Released to the public domain 16-Jan-2001,
3 # by Tim Peters (tim.one@home.com).
5 # Provided as-is; use at your own risk; no warranty; no promises; enjoy!
7 """Module doctest -- a framework for running examples in docstrings.
9 NORMAL USAGE
11 In normal use, end each module M with:
13 def _test():
14 import doctest, M # replace M with your module's name
15 return doctest.testmod(M) # ditto
17 if __name__ == "__main__":
18 _test()
20 Then running the module as a script will cause the examples in the
21 docstrings to get executed and verified:
23 python M.py
25 This won't display anything unless an example fails, in which case the
26 failing example(s) and the cause(s) of the failure(s) are printed to stdout
27 (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
28 line of output is "Test failed.".
30 Run it with the -v switch instead:
32 python M.py -v
34 and a detailed report of all examples tried is printed to stdout, along
35 with assorted summaries at the end.
37 You can force verbose mode by passing "verbose=1" to testmod, or prohibit
38 it by passing "verbose=0". In either of those cases, sys.argv is not
39 examined by testmod.
41 In any case, testmod returns a 2-tuple of ints (f, t), where f is the
42 number of docstring examples that failed and t is the total number of
43 docstring examples attempted.
46 WHICH DOCSTRINGS ARE EXAMINED?
48 + M.__doc__.
50 + f.__doc__ for all functions f in M.__dict__.values(), except those
51 with private names.
53 + C.__doc__ for all classes C in M.__dict__.values(), except those with
54 private names.
56 + If M.__test__ exists and "is true", it must be a dict, and
57 each entry maps a (string) name to a function object, class object, or
58 string. Function and class object docstrings found from M.__test__
59 are searched even if the name is private, and strings are searched
60 directly as if they were docstrings. In output, a key K in M.__test__
61 appears with name
62 <name of M>.__test__.K
64 Any classes found are recursively searched similarly, to test docstrings in
65 their contained methods and nested classes. Private names reached from M's
66 globals are skipped, but all names reached from M.__test__ are searched.
68 By default, a name is considered to be private if it begins with an
69 underscore (like "_my_func") but doesn't both begin and end with (at least)
70 two underscores (like "__init__"). You can change the default by passing
71 your own "isprivate" function to testmod.
73 If you want to test docstrings in objects with private names too, stuff
74 them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
75 own isprivate function to Tester's constructor, or call the rundoc method
76 of a Tester instance).
78 Warning: imports can cause trouble; e.g., if you do
80 from XYZ import XYZclass
82 then XYZclass is a name in M.__dict__ too, and doctest has no way to know
83 that XYZclass wasn't *defined* in M. So it may try to execute the examples
84 in XYZclass's docstring, and those in turn may require a different set of
85 globals to work correctly. I prefer to do "import *"- friendly imports,
86 a la
88 import XYY
89 _XYZclass = XYZ.XYZclass
90 del XYZ
92 or (Python 2.0)
94 from XYZ import XYZclass as _XYZclass
96 and then the leading underscore stops testmod from going nuts. You may
97 prefer the method in the next section.
100 WHAT'S THE EXECUTION CONTEXT?
102 By default, each time testmod finds a docstring to test, it uses a *copy*
103 of M's globals (so that running tests on a module doesn't change the
104 module's real globals, and so that one test in M can't leave behind crumbs
105 that accidentally allow another test to work). This means examples can
106 freely use any names defined at top-level in M. It also means that sloppy
107 imports (see above) can cause examples in external docstrings to use
108 globals inappropriate for them.
110 You can force use of your own dict as the execution context by passing
111 "globs=your_dict" to testmod instead. Presumably this would be a copy of
112 M.__dict__ merged with the globals from other imported modules.
115 WHAT IF I WANT TO TEST A WHOLE PACKAGE?
117 Piece o' cake, provided the modules do their testing from docstrings.
118 Here's the test.py I use for the world's most elaborate Rational/
119 floating-base-conversion pkg (which I'll distribute some day):
121 from Rational import Cvt
122 from Rational import Format
123 from Rational import machprec
124 from Rational import Rat
125 from Rational import Round
126 from Rational import utils
128 modules = (Cvt,
129 Format,
130 machprec,
131 Rat,
132 Round,
133 utils)
135 def _test():
136 import doctest
137 import sys
138 verbose = "-v" in sys.argv
139 for mod in modules:
140 doctest.testmod(mod, verbose=verbose, report=0)
141 doctest.master.summarize()
143 if __name__ == "__main__":
144 _test()
146 IOW, it just runs testmod on all the pkg modules. testmod remembers the
147 names and outcomes (# of failures, # of tries) for each item it's seen, and
148 passing "report=0" prevents it from printing a summary in verbose mode.
149 Instead, the summary is delayed until all modules have been tested, and
150 then "doctest.master.summarize()" forces the summary at the end.
152 So this is very nice in practice: each module can be tested individually
153 with almost no work beyond writing up docstring examples, and collections
154 of modules can be tested too as a unit with no more work than the above.
157 WHAT ABOUT EXCEPTIONS?
159 No problem, as long as the only output generated by the example is the
160 traceback itself. For example:
162 >>> [1, 2, 3].remove(42)
163 Traceback (most recent call last):
164 File "<stdin>", line 1, in ?
165 ValueError: list.remove(x): x not in list
168 Note that only the exception type and value are compared (specifically,
169 only the last line in the traceback).
172 ADVANCED USAGE
174 doctest.testmod() captures the testing policy I find most useful most
175 often. You may want other policies.
177 testmod() actually creates a local instance of class doctest.Tester, runs
178 appropriate methods of that class, and merges the results into global
179 Tester instance doctest.master.
181 You can create your own instances of doctest.Tester, and so build your own
182 policies, or even run methods of doctest.master directly. See
183 doctest.Tester.__doc__ for details.
186 SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
188 Oh ya. It's easy! In most cases a copy-and-paste of an interactive
189 console session works fine -- just make sure the leading whitespace is
190 rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
191 right, but doctest is not in the business of guessing what you think a tab
192 means).
194 >>> # comments are ignored
195 >>> x = 12
196 >>> x
198 >>> if x == 13:
199 ... print "yes"
200 ... else:
201 ... print "no"
202 ... print "NO"
203 ... print "NO!!!"
207 NO!!!
210 Any expected output must immediately follow the final ">>>" or "..." line
211 containing the code, and the expected output (if any) extends to the next
212 ">>>" or all-whitespace line. That's it.
214 Bummers:
216 + Expected output cannot contain an all-whitespace line, since such a line
217 is taken to signal the end of expected output.
219 + Output to stdout is captured, but not output to stderr (exception
220 tracebacks are captured via a different means).
222 + If you continue a line via backslashing in an interactive session, or for
223 any other reason use a backslash, you need to double the backslash in the
224 docstring version. This is simply because you're in a string, and so the
225 backslash must be escaped for it to survive intact. Like:
227 >>> if "yes" == \\
228 ... "y" + \\
229 ... "es": # in the source code you'll see the doubled backslashes
230 ... print 'yes'
233 The starting column doesn't matter:
235 >>> assert "Easy!"
236 >>> import math
237 >>> math.floor(1.9)
240 and as many leading whitespace characters are stripped from the expected
241 output as appeared in the initial ">>>" line that triggered it.
243 If you execute this very file, the examples above will be found and
244 executed, leading to this output in verbose mode:
246 Running doctest.__doc__
247 Trying: [1, 2, 3].remove(42)
248 Expecting:
249 Traceback (most recent call last):
250 File "<stdin>", line 1, in ?
251 ValueError: list.remove(x): x not in list
253 Trying: x = 12
254 Expecting: nothing
256 Trying: x
257 Expecting: 12
259 Trying:
260 if x == 13:
261 print "yes"
262 else:
263 print "no"
264 print "NO"
265 print "NO!!!"
266 Expecting:
269 NO!!!
271 ... and a bunch more like that, with this summary at the end:
273 5 items had no tests:
274 doctest.Tester.__init__
275 doctest.Tester.run__test__
276 doctest.Tester.summarize
277 doctest.run_docstring_examples
278 doctest.testmod
279 12 items passed all tests:
280 8 tests in doctest
281 6 tests in doctest.Tester
282 10 tests in doctest.Tester.merge
283 7 tests in doctest.Tester.rundict
284 3 tests in doctest.Tester.rundoc
285 3 tests in doctest.Tester.runstring
286 2 tests in doctest.__test__._TestClass
287 2 tests in doctest.__test__._TestClass.__init__
288 2 tests in doctest.__test__._TestClass.get
289 1 tests in doctest.__test__._TestClass.square
290 2 tests in doctest.__test__.string
291 7 tests in doctest.is_private
292 53 tests in 17 items.
293 53 passed and 0 failed.
294 Test passed.
297 # 0,0,1 06-Mar-1999
298 # initial version posted
299 # 0,0,2 06-Mar-1999
300 # loosened parsing:
301 # cater to stinkin' tabs
302 # don't insist on a blank after PS2 prefix
303 # so trailing "... " line from a compound stmt no longer
304 # breaks if the file gets whitespace-trimmed
305 # better error msgs for inconsistent leading whitespace
306 # 0,9,1 08-Mar-1999
307 # exposed the Tester class and added client methods
308 # plus docstring examples of their use (eww - head-twisting!)
309 # fixed logic error in reporting total # of tests & failures
310 # added __test__ support to testmod (a pale reflection of Christian
311 # Tismer's vision ...)
312 # removed the "deep" argument; fiddle __test__ instead
313 # simplified endcase logic for extracting tests, and running them.
314 # before, if no output was expected but some was produced
315 # anyway via an eval'ed result, the discrepancy wasn't caught
316 # made TestClass private and used __test__ to get at it
317 # many doc updates
318 # speed _SpoofOut for long expected outputs
319 # 0,9,2 09-Mar-1999
320 # throw out comments from examples, enabling use of the much simpler
321 # exec compile(... "single") ...
322 # for simulating the runtime; that barfs on comment-only lines
323 # used the traceback module to do a much better job of reporting
324 # exceptions
325 # run __doc__ values thru str(), "just in case"
326 # privateness of names now determined by an overridable "isprivate"
327 # function
328 # by default a name now considered to be private iff it begins with
329 # an underscore but doesn't both begin & end with two of 'em; so
330 # e.g. Class.__init__ etc are searched now -- as they always
331 # should have been
332 # 0,9,3 18-Mar-1999
333 # added .flush stub to _SpoofOut (JPython buglet diagnosed by
334 # Hugh Emberson)
335 # repaired ridiculous docs about backslashes in examples
336 # minor internal changes
337 # changed source to Unix line-end conventions
338 # moved __test__ logic into new Tester.run__test__ method
339 # 0,9,4 27-Mar-1999
340 # report item name and line # in failing examples
341 # 0,9,5 29-Jun-1999
342 # allow straightforward exceptions in examples - thanks to Mark Hammond!
343 # 0,9,6 16-Jan-2001
344 # fiddling for changes in Python 2.0: some of the embedded docstring
345 # examples no longer worked *exactly* as advertised, due to minor
346 # language changes, and running doctest on itself pointed that out.
347 # Hard to think of a better example of why this is useful <wink>.
348 # 0,9,7 9-Feb-2001
349 # string method conversion
351 __version__ = 0, 9, 7
353 import types
354 _FunctionType = types.FunctionType
355 _ClassType = types.ClassType
356 _ModuleType = types.ModuleType
357 _StringType = types.StringType
358 del types
360 import re
361 PS1 = ">>>"
362 PS2 = "..."
363 _isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
364 _isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
365 _isEmpty = re.compile(r"\s*$").match
366 _isComment = re.compile(r"\s*#").match
367 del re
369 __all__ = []
371 # Extract interactive examples from a string. Return a list of triples,
372 # (source, outcome, lineno). "source" is the source code, and ends
373 # with a newline iff the source spans more than one line. "outcome" is
374 # the expected output if any, else an empty string. When not empty,
375 # outcome always ends with a newline. "lineno" is the line number,
376 # 0-based wrt the start of the string, of the first source line.
378 def _extract_examples(s):
379 isPS1, isPS2 = _isPS1, _isPS2
380 isEmpty, isComment = _isEmpty, _isComment
381 examples = []
382 lines = s.split("\n")
383 i, n = 0, len(lines)
384 while i < n:
385 line = lines[i]
386 i = i + 1
387 m = isPS1(line)
388 if m is None:
389 continue
390 j = m.end(0) # beyond the prompt
391 if isEmpty(line, j) or isComment(line, j):
392 # a bare prompt or comment -- not interesting
393 continue
394 lineno = i - 1
395 if line[j] != " ":
396 raise ValueError("line " + `lineno` + " of docstring lacks "
397 "blank after " + PS1 + ": " + line)
398 j = j + 1
399 blanks = m.group(1)
400 nblanks = len(blanks)
401 # suck up this and following PS2 lines
402 source = []
403 while 1:
404 source.append(line[j:])
405 line = lines[i]
406 m = isPS2(line)
407 if m:
408 if m.group(1) != blanks:
409 raise ValueError("inconsistent leading whitespace "
410 "in line " + `i` + " of docstring: " + line)
411 i = i + 1
412 else:
413 break
414 if len(source) == 1:
415 source = source[0]
416 else:
417 # get rid of useless null line from trailing empty "..."
418 if source[-1] == "":
419 del source[-1]
420 source = "\n".join(source) + "\n"
421 # suck up response
422 if isPS1(line) or isEmpty(line):
423 expect = ""
424 else:
425 expect = []
426 while 1:
427 if line[:nblanks] != blanks:
428 raise ValueError("inconsistent leading whitespace "
429 "in line " + `i` + " of docstring: " + line)
430 expect.append(line[nblanks:])
431 i = i + 1
432 line = lines[i]
433 if isPS1(line) or isEmpty(line):
434 break
435 expect = "\n".join(expect) + "\n"
436 examples.append( (source, expect, lineno) )
437 return examples
439 # Capture stdout when running examples.
441 class _SpoofOut:
442 def __init__(self):
443 self.clear()
444 def write(self, s):
445 self.buf.append(s)
446 def get(self):
447 guts = "".join(self.buf)
448 # If anything at all was written, make sure there's a trailing
449 # newline. There's no way for the expected output to indicate
450 # that a trailing newline is missing.
451 if guts and not guts.endswith("\n"):
452 guts = guts + "\n"
453 return guts
454 def clear(self):
455 self.buf = []
456 def flush(self):
457 # JPython calls flush
458 pass
460 # Display some tag-and-msg pairs nicely, keeping the tag and its msg
461 # on the same line when that makes sense.
463 def _tag_out(printer, *tag_msg_pairs):
464 for tag, msg in tag_msg_pairs:
465 printer(tag + ":")
466 msg_has_nl = msg[-1:] == "\n"
467 msg_has_two_nl = msg_has_nl and \
468 msg.find("\n") < len(msg) - 1
469 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
470 printer(" ")
471 else:
472 printer("\n")
473 printer(msg)
474 if not msg_has_nl:
475 printer("\n")
477 # Run list of examples, in context globs. "out" can be used to display
478 # stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
479 # that captures the examples' std output. Return (#failures, #tries).
481 def _run_examples_inner(out, fakeout, examples, globs, verbose, name):
482 import sys, traceback
483 OK, BOOM, FAIL = range(3)
484 NADA = "nothing"
485 stderr = _SpoofOut()
486 failures = 0
487 for source, want, lineno in examples:
488 if verbose:
489 _tag_out(out, ("Trying", source),
490 ("Expecting", want or NADA))
491 fakeout.clear()
492 try:
493 exec compile(source, "<string>", "single") in globs
494 got = fakeout.get()
495 state = OK
496 except:
497 # See whether the exception was expected.
498 if want.find("Traceback (innermost last):\n") == 0 or \
499 want.find("Traceback (most recent call last):\n") == 0:
500 # Only compare exception type and value - the rest of
501 # the traceback isn't necessary.
502 want = want.split('\n')[-2] + '\n'
503 exc_type, exc_val, exc_tb = sys.exc_info()
504 got = traceback.format_exception_only(exc_type, exc_val)[0]
505 state = OK
506 else:
507 # unexpected exception
508 stderr.clear()
509 traceback.print_exc(file=stderr)
510 state = BOOM
512 if state == OK:
513 if got == want:
514 if verbose:
515 out("ok\n")
516 continue
517 state = FAIL
519 assert state in (FAIL, BOOM)
520 failures = failures + 1
521 out("*" * 65 + "\n")
522 _tag_out(out, ("Failure in example", source))
523 out("from line #" + `lineno` + " of " + name + "\n")
524 if state == FAIL:
525 _tag_out(out, ("Expected", want or NADA), ("Got", got))
526 else:
527 assert state == BOOM
528 _tag_out(out, ("Exception raised", stderr.get()))
530 return failures, len(examples)
532 # Run list of examples, in context globs. Return (#failures, #tries).
534 def _run_examples(examples, globs, verbose, name):
535 import sys
536 saveout = sys.stdout
537 try:
538 sys.stdout = fakeout = _SpoofOut()
539 x = _run_examples_inner(saveout.write, fakeout, examples,
540 globs, verbose, name)
541 finally:
542 sys.stdout = saveout
543 return x
545 def run_docstring_examples(f, globs, verbose=0, name="NoName"):
546 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
548 Use dict globs as the globals for execution.
549 Return (#failures, #tries).
551 If optional arg verbose is true, print stuff even if there are no
552 failures.
553 Use string name in failure msgs.
556 try:
557 doc = f.__doc__
558 if not doc:
559 # docstring empty or None
560 return 0, 0
561 # just in case CT invents a doc object that has to be forced
562 # to look like a string <0.9 wink>
563 doc = str(doc)
564 except:
565 return 0, 0
567 e = _extract_examples(doc)
568 if not e:
569 return 0, 0
570 return _run_examples(e, globs, verbose, name)
572 def is_private(prefix, base):
573 """prefix, base -> true iff name prefix + "." + base is "private".
575 Prefix may be an empty string, and base does not contain a period.
576 Prefix is ignored (although functions you write conforming to this
577 protocol may make use of it).
578 Return true iff base begins with an (at least one) underscore, but
579 does not both begin and end with (at least) two underscores.
581 >>> is_private("a.b", "my_func")
583 >>> is_private("____", "_my_func")
585 >>> is_private("someclass", "__init__")
587 >>> is_private("sometypo", "__init_")
589 >>> is_private("x.y.z", "_")
591 >>> is_private("_x.y.z", "__")
593 >>> is_private("", "") # senseless but consistent
597 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
599 class Tester:
600 """Class Tester -- runs docstring examples and accumulates stats.
602 In normal use, function doctest.testmod() hides all this from you,
603 so use that if you can. Create your own instances of Tester to do
604 fancier things.
606 Methods:
607 runstring(s, name)
608 Search string s for examples to run; use name for logging.
609 Return (#failures, #tries).
611 rundoc(object, name=None)
612 Search object.__doc__ for examples to run; use name (or
613 object.__name__) for logging. Return (#failures, #tries).
615 rundict(d, name)
616 Search for examples in docstrings in all of d.values(); use name
617 for logging. Return (#failures, #tries).
619 run__test__(d, name)
620 Treat dict d like module.__test__. Return (#failures, #tries).
622 summarize(verbose=None)
623 Display summary of testing results, to stdout. Return
624 (#failures, #tries).
626 merge(other)
627 Merge in the test results from Tester instance "other".
629 >>> from doctest import Tester
630 >>> t = Tester(globs={'x': 42}, verbose=0)
631 >>> t.runstring(r'''
632 ... >>> x = x * 2
633 ... >>> print x
634 ... 42
635 ... ''', 'XYZ')
636 *****************************************************************
637 Failure in example: print x
638 from line #2 of XYZ
639 Expected: 42
640 Got: 84
641 (1, 2)
642 >>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
643 (0, 2)
644 >>> t.summarize()
645 1 items had failures:
646 1 of 2 in XYZ
647 ***Test Failed*** 1 failures.
648 (1, 4)
649 >>> t.summarize(verbose=1)
650 1 items passed all tests:
651 2 tests in example2
652 1 items had failures:
653 1 of 2 in XYZ
654 4 tests in 2 items.
655 3 passed and 1 failed.
656 ***Test Failed*** 1 failures.
657 (1, 4)
661 def __init__(self, mod=None, globs=None, verbose=None,
662 isprivate=None):
663 """mod=None, globs=None, verbose=None, isprivate=None
665 See doctest.__doc__ for an overview.
667 Optional keyword arg "mod" is a module, whose globals are used for
668 executing examples. If not specified, globs must be specified.
670 Optional keyword arg "globs" gives a dict to be used as the globals
671 when executing examples; if not specified, use the globals from
672 module mod.
674 In either case, a copy of the dict is used for each docstring
675 examined.
677 Optional keyword arg "verbose" prints lots of stuff if true, only
678 failures if false; by default, it's true iff "-v" is in sys.argv.
680 Optional keyword arg "isprivate" specifies a function used to determine
681 whether a name is private. The default function is doctest.is_private;
682 see its docs for details.
685 if mod is None and globs is None:
686 raise TypeError("Tester.__init__: must specify mod or globs")
687 if mod is not None and type(mod) is not _ModuleType:
688 raise TypeError("Tester.__init__: mod must be a module; " +
689 `mod`)
690 if globs is None:
691 globs = mod.__dict__
692 self.globs = globs
694 if verbose is None:
695 import sys
696 verbose = "-v" in sys.argv
697 self.verbose = verbose
699 if isprivate is None:
700 isprivate = is_private
701 self.isprivate = isprivate
703 self.name2ft = {} # map name to (#failures, #trials) pair
705 def runstring(self, s, name):
707 s, name -> search string s for examples to run, logging as name.
709 Use string name as the key for logging the outcome.
710 Return (#failures, #examples).
712 >>> t = Tester(globs={}, verbose=1)
713 >>> test = r'''
714 ... # just an example
715 ... >>> x = 1 + 2
716 ... >>> x
717 ... 3
718 ... '''
719 >>> t.runstring(test, "Example")
720 Running string Example
721 Trying: x = 1 + 2
722 Expecting: nothing
724 Trying: x
725 Expecting: 3
727 0 of 2 examples failed in string Example
728 (0, 2)
731 if self.verbose:
732 print "Running string", name
733 f = t = 0
734 e = _extract_examples(s)
735 if e:
736 f, t = _run_examples(e, self.globs.copy(), self.verbose, name)
737 if self.verbose:
738 print f, "of", t, "examples failed in string", name
739 self.__record_outcome(name, f, t)
740 return f, t
742 def rundoc(self, object, name=None):
744 object, name=None -> search object.__doc__ for examples to run.
746 Use optional string name as the key for logging the outcome;
747 by default use object.__name__.
748 Return (#failures, #examples).
749 If object is a class object, search recursively for method
750 docstrings too.
751 object.__doc__ is examined regardless of name, but if object is
752 a class, whether private names reached from object are searched
753 depends on the constructor's "isprivate" argument.
755 >>> t = Tester(globs={}, verbose=0)
756 >>> def _f():
757 ... '''Trivial docstring example.
758 ... >>> assert 2 == 2
759 ... '''
760 ... return 32
762 >>> t.rundoc(_f) # expect 0 failures in 1 example
763 (0, 1)
766 if name is None:
767 try:
768 name = object.__name__
769 except AttributeError:
770 raise ValueError("Tester.rundoc: name must be given "
771 "when object.__name__ doesn't exist; " + `object`)
772 if self.verbose:
773 print "Running", name + ".__doc__"
774 f, t = run_docstring_examples(object, self.globs.copy(),
775 self.verbose, name)
776 if self.verbose:
777 print f, "of", t, "examples failed in", name + ".__doc__"
778 self.__record_outcome(name, f, t)
779 if type(object) is _ClassType:
780 f2, t2 = self.rundict(object.__dict__, name)
781 f = f + f2
782 t = t + t2
783 return f, t
785 def rundict(self, d, name):
787 d. name -> search for docstring examples in all of d.values().
789 For k, v in d.items() such that v is a function or class,
790 do self.rundoc(v, name + "." + k). Whether this includes
791 objects with private names depends on the constructor's
792 "isprivate" argument.
793 Return aggregate (#failures, #examples).
795 >>> def _f():
796 ... '''>>> assert 1 == 1
797 ... '''
798 >>> def g():
799 ... '''>>> assert 2 != 1
800 ... '''
801 >>> d = {"_f": _f, "g": g}
802 >>> t = Tester(globs={}, verbose=0)
803 >>> t.rundict(d, "rundict_test") # _f is skipped
804 (0, 1)
805 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
806 >>> t.rundict(d, "rundict_test_pvt") # both are searched
807 (0, 2)
810 if not hasattr(d, "items"):
811 raise TypeError("Tester.rundict: d must support .items(); " +
812 `d`)
813 f = t = 0
814 for thisname, value in d.items():
815 if type(value) in (_FunctionType, _ClassType):
816 f2, t2 = self.__runone(value, name + "." + thisname)
817 f = f + f2
818 t = t + t2
819 return f, t
821 def run__test__(self, d, name):
822 """d, name -> Treat dict d like module.__test__.
824 Return (#failures, #tries).
825 See testmod.__doc__ for details.
828 failures = tries = 0
829 prefix = name + "."
830 savepvt = self.isprivate
831 try:
832 self.isprivate = lambda *args: 0
833 for k, v in d.items():
834 thisname = prefix + k
835 if type(v) is _StringType:
836 f, t = self.runstring(v, thisname)
837 elif type(v) in (_FunctionType, _ClassType):
838 f, t = self.rundoc(v, thisname)
839 else:
840 raise TypeError("Tester.run__test__: values in "
841 "dict must be strings, functions "
842 "or classes; " + `v`)
843 failures = failures + f
844 tries = tries + t
845 finally:
846 self.isprivate = savepvt
847 return failures, tries
849 def summarize(self, verbose=None):
851 verbose=None -> summarize results, return (#failures, #tests).
853 Print summary of test results to stdout.
854 Optional arg 'verbose' controls how wordy this is. By
855 default, use the verbose setting established by the
856 constructor.
859 if verbose is None:
860 verbose = self.verbose
861 notests = []
862 passed = []
863 failed = []
864 totalt = totalf = 0
865 for x in self.name2ft.items():
866 name, (f, t) = x
867 assert f <= t
868 totalt = totalt + t
869 totalf = totalf + f
870 if t == 0:
871 notests.append(name)
872 elif f == 0:
873 passed.append( (name, t) )
874 else:
875 failed.append(x)
876 if verbose:
877 if notests:
878 print len(notests), "items had no tests:"
879 notests.sort()
880 for thing in notests:
881 print " ", thing
882 if passed:
883 print len(passed), "items passed all tests:"
884 passed.sort()
885 for thing, count in passed:
886 print " %3d tests in %s" % (count, thing)
887 if failed:
888 print len(failed), "items had failures:"
889 failed.sort()
890 for thing, (f, t) in failed:
891 print " %3d of %3d in %s" % (f, t, thing)
892 if verbose:
893 print totalt, "tests in", len(self.name2ft), "items."
894 print totalt - totalf, "passed and", totalf, "failed."
895 if totalf:
896 print "***Test Failed***", totalf, "failures."
897 elif verbose:
898 print "Test passed."
899 return totalf, totalt
901 def merge(self, other):
903 other -> merge in test results from the other Tester instance.
905 If self and other both have a test result for something
906 with the same name, the (#failures, #tests) results are
907 summed, and a warning is printed to stdout.
909 >>> from doctest import Tester
910 >>> t1 = Tester(globs={}, verbose=0)
911 >>> t1.runstring('''
912 ... >>> x = 12
913 ... >>> print x
914 ... 12
915 ... ''', "t1example")
916 (0, 2)
918 >>> t2 = Tester(globs={}, verbose=0)
919 >>> t2.runstring('''
920 ... >>> x = 13
921 ... >>> print x
922 ... 13
923 ... ''', "t2example")
924 (0, 2)
925 >>> common = ">>> assert 1 + 2 == 3\\n"
926 >>> t1.runstring(common, "common")
927 (0, 1)
928 >>> t2.runstring(common, "common")
929 (0, 1)
930 >>> t1.merge(t2)
931 *** Tester.merge: 'common' in both testers; summing outcomes.
932 >>> t1.summarize(1)
933 3 items passed all tests:
934 2 tests in common
935 2 tests in t1example
936 2 tests in t2example
937 6 tests in 3 items.
938 6 passed and 0 failed.
939 Test passed.
940 (0, 6)
944 d = self.name2ft
945 for name, (f, t) in other.name2ft.items():
946 if d.has_key(name):
947 print "*** Tester.merge: '" + name + "' in both" \
948 " testers; summing outcomes."
949 f2, t2 = d[name]
950 f = f + f2
951 t = t + t2
952 d[name] = f, t
954 def __record_outcome(self, name, f, t):
955 if self.name2ft.has_key(name):
956 print "*** Warning: '" + name + "' was tested before;", \
957 "summing outcomes."
958 f2, t2 = self.name2ft[name]
959 f = f + f2
960 t = t + t2
961 self.name2ft[name] = f, t
963 def __runone(self, target, name):
964 if "." in name:
965 i = name.rindex(".")
966 prefix, base = name[:i], name[i+1:]
967 else:
968 prefix, base = "", base
969 if self.isprivate(prefix, base):
970 return 0, 0
971 return self.rundoc(target, name)
973 master = None
975 def testmod(m, name=None, globs=None, verbose=None, isprivate=None,
976 report=1):
977 """m, name=None, globs=None, verbose=None, isprivate=None, report=1
979 Test examples in docstrings in functions and classes reachable from
980 module m, starting with m.__doc__. Private names are skipped.
982 Also test examples reachable from dict m.__test__ if it exists and is
983 not None. m.__dict__ maps names to functions, classes and strings;
984 function and class docstrings are tested even if the name is private;
985 strings are tested directly, as if they were docstrings.
987 Return (#failures, #tests).
989 See doctest.__doc__ for an overview.
991 Optional keyword arg "name" gives the name of the module; by default
992 use m.__name__.
994 Optional keyword arg "globs" gives a dict to be used as the globals
995 when executing examples; by default, use m.__dict__. A copy of this
996 dict is actually used for each docstring, so that each docstring's
997 examples start with a clean slate.
999 Optional keyword arg "verbose" prints lots of stuff if true, prints
1000 only failures if false; by default, it's true iff "-v" is in sys.argv.
1002 Optional keyword arg "isprivate" specifies a function used to
1003 determine whether a name is private. The default function is
1004 doctest.is_private; see its docs for details.
1006 Optional keyword arg "report" prints a summary at the end when true,
1007 else prints nothing at the end. In verbose mode, the summary is
1008 detailed, else very brief (in fact, empty if all tests passed).
1010 Advanced tomfoolery: testmod runs methods of a local instance of
1011 class doctest.Tester, then merges the results into (or creates)
1012 global Tester instance doctest.master. Methods of doctest.master
1013 can be called directly too, if you want to do something unusual.
1014 Passing report=0 to testmod is especially useful then, to delay
1015 displaying a summary. Invoke doctest.master.summarize(verbose)
1016 when you're done fiddling.
1019 global master
1021 if type(m) is not _ModuleType:
1022 raise TypeError("testmod: module required; " + `m`)
1023 if name is None:
1024 name = m.__name__
1025 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate)
1026 failures, tries = tester.rundoc(m, name)
1027 f, t = tester.rundict(m.__dict__, name)
1028 failures = failures + f
1029 tries = tries + t
1030 if hasattr(m, "__test__"):
1031 testdict = m.__test__
1032 if testdict:
1033 if not hasattr(testdict, "items"):
1034 raise TypeError("testmod: module.__test__ must support "
1035 ".items(); " + `testdict`)
1036 f, t = tester.run__test__(testdict, name + ".__test__")
1037 failures = failures + f
1038 tries = tries + t
1039 if report:
1040 tester.summarize()
1041 if master is None:
1042 master = tester
1043 else:
1044 master.merge(tester)
1045 return failures, tries
1047 class _TestClass:
1049 A pointless class, for sanity-checking of docstring testing.
1051 Methods:
1052 square()
1053 get()
1055 >>> _TestClass(13).get() + _TestClass(-12).get()
1057 >>> hex(_TestClass(13).square().get())
1058 '0xa9'
1061 def __init__(self, val):
1062 """val -> _TestClass object with associated value val.
1064 >>> t = _TestClass(123)
1065 >>> print t.get()
1069 self.val = val
1071 def square(self):
1072 """square() -> square TestClass's associated value
1074 >>> _TestClass(13).square().get()
1078 self.val = self.val ** 2
1079 return self
1081 def get(self):
1082 """get() -> return TestClass's associated value.
1084 >>> x = _TestClass(-42)
1085 >>> print x.get()
1089 return self.val
1091 __test__ = {"_TestClass": _TestClass,
1092 "string": r"""
1093 Example of a string object, searched as-is.
1094 >>> x = 1; y = 2
1095 >>> x + y, x * y
1096 (3, 2)
1100 def _test():
1101 import doctest
1102 return doctest.testmod(doctest)
1104 if __name__ == "__main__":
1105 _test()