7 """Module doctest -- a framework for running examples in docstrings.
11 In normal use, end each module M with:
14 import doctest, M # replace M with your module's name
15 return doctest.testmod(M) # ditto
17 if __name__ == "__main__":
20 Then running the module as a script will cause the examples in the
21 docstrings to get executed and verified:
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:
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
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?
50 + f.__doc__ for all functions f in M.__dict__.values(), except those
51 with private names and those defined in other modules.
53 + C.__doc__ for all classes C in M.__dict__.values(), except those with
54 private names and those defined in other modules.
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__
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 WHAT'S THE EXECUTION CONTEXT?
80 By default, each time testmod finds a docstring to test, it uses a *copy*
81 of M's globals (so that running tests on a module doesn't change the
82 module's real globals, and so that one test in M can't leave behind crumbs
83 that accidentally allow another test to work). This means examples can
84 freely use any names defined at top-level in M. It also means that sloppy
85 imports (see above) can cause examples in external docstrings to use
86 globals inappropriate for them.
88 You can force use of your own dict as the execution context by passing
89 "globs=your_dict" to testmod instead. Presumably this would be a copy of
90 M.__dict__ merged with the globals from other imported modules.
93 WHAT IF I WANT TO TEST A WHOLE PACKAGE?
95 Piece o' cake, provided the modules do their testing from docstrings.
96 Here's the test.py I use for the world's most elaborate Rational/
97 floating-base-conversion pkg (which I'll distribute some day):
99 from Rational import Cvt
100 from Rational import Format
101 from Rational import machprec
102 from Rational import Rat
103 from Rational import Round
104 from Rational import utils
116 verbose = "-v" in sys.argv
118 doctest.testmod(mod, verbose=verbose, report=0)
119 doctest.master.summarize()
121 if __name__ == "__main__":
124 IOW, it just runs testmod on all the pkg modules. testmod remembers the
125 names and outcomes (# of failures, # of tries) for each item it's seen, and
126 passing "report=0" prevents it from printing a summary in verbose mode.
127 Instead, the summary is delayed until all modules have been tested, and
128 then "doctest.master.summarize()" forces the summary at the end.
130 So this is very nice in practice: each module can be tested individually
131 with almost no work beyond writing up docstring examples, and collections
132 of modules can be tested too as a unit with no more work than the above.
135 WHAT ABOUT EXCEPTIONS?
137 No problem, as long as the only output generated by the example is the
138 traceback itself. For example:
140 >>> [1, 2, 3].remove(42)
141 Traceback (most recent call last):
142 File "<stdin>", line 1, in ?
143 ValueError: list.remove(x): x not in list
146 Note that only the exception type and value are compared (specifically,
147 only the last line in the traceback).
152 doctest.testmod() captures the testing policy I find most useful most
153 often. You may want other policies.
155 testmod() actually creates a local instance of class doctest.Tester, runs
156 appropriate methods of that class, and merges the results into global
157 Tester instance doctest.master.
159 You can create your own instances of doctest.Tester, and so build your own
160 policies, or even run methods of doctest.master directly. See
161 doctest.Tester.__doc__ for details.
164 SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
166 Oh ya. It's easy! In most cases a copy-and-paste of an interactive
167 console session works fine -- just make sure the leading whitespace is
168 rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
169 right, but doctest is not in the business of guessing what you think a tab
172 >>> # comments are ignored
188 Any expected output must immediately follow the final ">>>" or "..." line
189 containing the code, and the expected output (if any) extends to the next
190 ">>>" or all-whitespace line. That's it.
194 + Expected output cannot contain an all-whitespace line, since such a line
195 is taken to signal the end of expected output.
197 + Output to stdout is captured, but not output to stderr (exception
198 tracebacks are captured via a different means).
200 + If you continue a line via backslashing in an interactive session, or for
201 any other reason use a backslash, you need to double the backslash in the
202 docstring version. This is simply because you're in a string, and so the
203 backslash must be escaped for it to survive intact. Like:
207 ... "es": # in the source code you'll see the doubled backslashes
211 The starting column doesn't matter:
218 and as many leading whitespace characters are stripped from the expected
219 output as appeared in the initial ">>>" line that triggered it.
221 If you execute this very file, the examples above will be found and
222 executed, leading to this output in verbose mode:
224 Running doctest.__doc__
225 Trying: [1, 2, 3].remove(42)
227 Traceback (most recent call last):
228 File "<stdin>", line 1, in ?
229 ValueError: list.remove(x): x not in list
249 ... and a bunch more like that, with this summary at the end:
251 5 items had no tests:
252 doctest.Tester.__init__
253 doctest.Tester.run__test__
254 doctest.Tester.summarize
255 doctest.run_docstring_examples
257 12 items passed all tests:
259 6 tests in doctest.Tester
260 10 tests in doctest.Tester.merge
261 14 tests in doctest.Tester.rundict
262 3 tests in doctest.Tester.rundoc
263 3 tests in doctest.Tester.runstring
264 2 tests in doctest.__test__._TestClass
265 2 tests in doctest.__test__._TestClass.__init__
266 2 tests in doctest.__test__._TestClass.get
267 1 tests in doctest.__test__._TestClass.square
268 2 tests in doctest.__test__.string
269 7 tests in doctest.is_private
270 60 tests in 17 items.
271 60 passed and 0 failed.
277 'run_docstring_examples',
287 _isPS1 = re.compile(
r"(\s*)" + re.escape(PS1)).match
288 _isPS2 = re.compile(
r"(\s*)" + re.escape(PS2)).match
289 _isEmpty = re.compile(
r"\s*$").match
290 _isComment = re.compile(
r"\s*#").match
293 from types
import StringTypes
as _StringTypes
295 from inspect
import isclass
as _isclass
296 from inspect
import isfunction
as _isfunction
297 from inspect
import ismodule
as _ismodule
298 from inspect
import classify_class_attrs
as _classify_class_attrs
307 def _extract_examples(s):
308 isPS1, isPS2 = _isPS1, _isPS2
309 isEmpty, isComment = _isEmpty, _isComment
311 lines = s.split(
"\n")
320 if isEmpty(line, j)
or isComment(line, j):
325 raise ValueError(
"line " + `lineno` +
" of docstring lacks "
326 "blank after " + PS1 +
": " + line)
329 nblanks = len(blanks)
333 source.append(line[j:])
337 if m.group(1) != blanks:
338 raise ValueError(
"inconsistent leading whitespace "
339 "in line " + `i` +
" of docstring: " + line)
349 source =
"\n".
join(source) +
"\n"
351 if isPS1(line)
or isEmpty(line):
356 if line[:nblanks] != blanks:
357 raise ValueError(
"inconsistent leading whitespace "
358 "in line " + `i` +
" of docstring: " + line)
359 expect.append(line[nblanks:])
362 if isPS1(line)
or isEmpty(line):
364 expect =
"\n".
join(expect) +
"\n"
365 examples.append( (source, expect, lineno) )
380 if guts
and not guts.endswith(
"\n"):
384 if hasattr(self,
"softspace"):
389 if hasattr(self,
"softspace"):
398 def _tag_out(printer, *tag_msg_pairs):
399 for tag, msg
in tag_msg_pairs:
401 msg_has_nl = msg[-1:] ==
"\n"
402 msg_has_two_nl = msg_has_nl
and \
403 msg.find(
"\n") < len(msg) - 1
404 if len(tag) + len(msg) < 76
and not msg_has_two_nl:
416 def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
418 import sys, traceback
419 OK, BOOM, FAIL = range(3)
423 for source, want, lineno
in examples:
425 _tag_out(out, (
"Trying", source),
426 (
"Expecting", want
or NADA))
429 exec
compile(source,
"<string>",
"single",
430 compileflags, 1)
in globs
435 if want.find(
"Traceback (innermost last):\n") == 0
or \
436 want.find(
"Traceback (most recent call last):\n") == 0:
439 want = want.split(
'\n')[-2] +
'\n'
440 exc_type, exc_val = sys.exc_info()[:2]
456 assert state
in (FAIL, BOOM)
457 failures = failures + 1
459 _tag_out(out, (
"Failure in example", source))
460 out(
"from line #" + `lineno` +
" of " + name +
"\n")
462 _tag_out(out, (
"Expected", want
or NADA), (
"Got", got))
465 _tag_out(out, (
"Exception raised", stderr.get()))
467 return failures, len(examples)
472 def _extract_future_flags(globs):
474 for fname
in __future__.all_feature_names:
475 feature = globs.get(fname,
None)
476 if feature
is getattr(__future__, fname):
477 flags |= feature.compiler_flag
483 def _run_examples(examples, globs, verbose, name, compileflags):
488 sys.stdout = fakeout = _SpoofOut()
489 x = _run_examples_inner(saveout.write, fakeout, examples,
490 globs, verbose, name, compileflags)
506 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
508 Use (a shallow copy of) dict globs as the globals for execution.
509 Return (#failures, #tries).
511 If optional arg verbose is true, print stuff even if there are no
513 Use string name in failure msgs.
527 e = _extract_examples(doc)
530 if compileflags
is None:
531 compileflags = _extract_future_flags(globs)
532 return _run_examples(e, globs, verbose, name, compileflags)
535 """prefix, base -> true iff name prefix + "." + base is "private".
537 Prefix may be an empty string, and base does not contain a period.
538 Prefix is ignored (although functions you write conforming to this
539 protocol may make use of it).
540 Return true iff base begins with an (at least one) underscore, but
541 does not both begin and end with (at least) two underscores.
543 >>> is_private("a.b", "my_func")
545 >>> is_private("____", "_my_func")
547 >>> is_private("someclass", "__init__")
549 >>> is_private("sometypo", "__init_")
551 >>> is_private("x.y.z", "_")
553 >>> is_private("_x.y.z", "__")
555 >>> is_private("", "") # senseless but consistent
559 return base[:1] ==
"_" and not base[:2] ==
"__" == base[-2:]
563 def _from_module(module, object):
564 if _isfunction(object):
565 return module.__dict__
is object.func_globals
567 return module.__name__ == object.__module__
568 raise ValueError(
"object must be a class or function")
571 """Class Tester -- runs docstring examples and accumulates stats.
573 In normal use, function doctest.testmod() hides all this from you,
574 so use that if you can. Create your own instances of Tester to do
579 Search string s for examples to run; use name for logging.
580 Return (#failures, #tries).
582 rundoc(object, name=None)
583 Search object.__doc__ for examples to run; use name (or
584 object.__name__) for logging. Return (#failures, #tries).
586 rundict(d, name, module=None)
587 Search for examples in docstrings in all of d.values(); use name
588 for logging. Exclude functions and classes not defined in module
589 if specified. Return (#failures, #tries).
592 Treat dict d like module.__test__. Return (#failures, #tries).
594 summarize(verbose=None)
595 Display summary of testing results, to stdout. Return
599 Merge in the test results from Tester instance "other".
601 >>> from doctest import Tester
602 >>> t = Tester(globs={'x': 42}, verbose=0)
608 *****************************************************************
609 Failure in example: print x
614 >>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
617 *****************************************************************
618 1 items had failures:
620 ***Test Failed*** 1 failures.
622 >>> t.summarize(verbose=1)
623 1 items passed all tests:
625 *****************************************************************
626 1 items had failures:
629 3 passed and 1 failed.
630 ***Test Failed*** 1 failures.
635 def __init__(self, mod=None, globs=None, verbose=None,
637 """mod=None, globs=None, verbose=None, isprivate=None
639 See doctest.__doc__ for an overview.
641 Optional keyword arg "mod" is a module, whose globals are used for
642 executing examples. If not specified, globs must be specified.
644 Optional keyword arg "globs" gives a dict to be used as the globals
645 when executing examples; if not specified, use the globals from
648 In either case, a copy of the dict is used for each docstring
651 Optional keyword arg "verbose" prints lots of stuff if true, only
652 failures if false; by default, it's true iff "-v" is in sys.argv.
654 Optional keyword arg "isprivate" specifies a function used to determine
655 whether a name is private. The default function is doctest.is_private;
656 see its docs for details.
659 if mod
is None and globs
is None:
660 raise TypeError(
"Tester.__init__: must specify mod or globs")
661 if mod
is not None and not _ismodule(mod):
662 raise TypeError(
"Tester.__init__: mod must be a module; " +
670 verbose =
"-v" in sys.argv
673 if isprivate
is None:
674 isprivate = is_private
683 s, name -> search string s for examples to run, logging as name.
685 Use string name as the key for logging the outcome.
686 Return (#failures, #examples).
688 >>> t = Tester(globs={}, verbose=1)
690 ... # just an example
695 >>> t.runstring(test, "Example")
696 Running string Example
703 0 of 2 examples failed in string Example
708 print "Running string", name
710 e = _extract_examples(s)
715 print f,
"of", t,
"examples failed in string", name
721 object, name=None -> search object.__doc__ for examples to run.
723 Use optional string name as the key for logging the outcome;
724 by default use object.__name__.
725 Return (#failures, #examples).
726 If object is a class object, search recursively for method
728 object.__doc__ is examined regardless of name, but if object is
729 a class, whether private names reached from object are searched
730 depends on the constructor's "isprivate" argument.
732 >>> t = Tester(globs={}, verbose=0)
734 ... '''Trivial docstring example.
735 ... >>> assert 2 == 2
739 >>> t.rundoc(_f) # expect 0 failures in 1 example
745 name = object.__name__
746 except AttributeError:
747 raise ValueError(
"Tester.rundoc: name must be given "
748 "when object.__name__ doesn't exist; " + `object`)
750 print "Running", name +
".__doc__"
754 print f,
"of", t,
"examples failed in", name +
".__doc__"
760 for tag, kind, homecls, value
in _classify_class_attrs(object):
762 if homecls
is not object:
769 elif kind ==
"method":
773 elif kind ==
"static method":
775 d[tag] = getattr(object, tag)
777 elif kind ==
"class method":
782 d[tag] = getattr(object, tag).im_func
784 elif kind ==
"property":
787 if value.__doc__
is not None:
788 d[tag] =
str(value.__doc__)
796 raise ValueError(
"teach doctest about %r" % kind)
806 d, name, module=None -> search for docstring examples in d.values().
808 For k, v in d.items() such that v is a function or class,
809 do self.rundoc(v, name + "." + k). Whether this includes
810 objects with private names depends on the constructor's
811 "isprivate" argument. If module is specified, functions and
812 classes that are not defined in module are excluded.
813 Return aggregate (#failures, #examples).
815 Build and populate two modules with sample functions to test that
816 exclusion of external functions and classes works.
819 >>> m1 = new.module('_m1')
820 >>> m2 = new.module('_m2')
823 ... '''>>> assert 1 == 1
826 ... '''>>> assert 2 != 1
829 ... '''>>> assert 2 > 1
832 ... '''>>> assert 1 < 2
835 >>> exec test_data in m1.__dict__
836 >>> exec test_data in m2.__dict__
837 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
839 Tests that objects outside m1 are excluded:
841 >>> t = Tester(globs={}, verbose=0)
842 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
845 Again, but with a custom isprivate function allowing _f:
847 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
848 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
851 And once more, not excluding stuff outside m1:
853 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
854 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
857 The exclusion of objects from outside the designated module is
858 meant to be invoked automagically by testmod.
865 if not hasattr(d,
"items"):
866 raise TypeError(
"Tester.rundict: d must support .items(); " +
873 for thisname
in names:
875 if _isfunction(value)
or _isclass(value):
876 if module
and not _from_module(module, value):
878 f2, t2 = self.
__runone(value, name +
"." + thisname)
884 """d, name -> Treat dict d like module.__test__.
886 Return (#failures, #tries).
887 See testmod.__doc__ for details.
901 thisname = prefix + k
902 if type(v)
in _StringTypes:
904 elif _isfunction(v)
or _isclass(v):
905 f, t = self.
rundoc(v, thisname)
907 raise TypeError(
"Tester.run__test__: values in "
908 "dict must be strings, functions "
909 "or classes; " + `v`)
910 failures = failures + f
914 return failures, tries
918 verbose=None -> summarize results, return (#failures, #tests).
920 Print summary of test results to stdout.
921 Optional arg 'verbose' controls how wordy this is. By
922 default, use the verbose setting established by the
932 for x
in self.name2ft.items():
940 passed.append( (name, t) )
945 print len(notests),
"items had no tests:"
947 for thing
in notests:
950 print len(passed),
"items passed all tests:"
952 for thing, count
in passed:
953 print " %3d tests in %s" % (count, thing)
956 print len(failed),
"items had failures:"
958 for thing, (f, t)
in failed:
959 print " %3d of %3d in %s" % (f, t, thing)
961 print totalt,
"tests in", len(self.
name2ft),
"items."
962 print totalt - totalf,
"passed and", totalf,
"failed."
964 print "***Test Failed***", totalf,
"failures."
967 return totalf, totalt
971 other -> merge in test results from the other Tester instance.
973 If self and other both have a test result for something
974 with the same name, the (#failures, #tests) results are
975 summed, and a warning is printed to stdout.
977 >>> from doctest import Tester
978 >>> t1 = Tester(globs={}, verbose=0)
983 ... ''', "t1example")
986 >>> t2 = Tester(globs={}, verbose=0)
991 ... ''', "t2example")
993 >>> common = ">>> assert 1 + 2 == 3\\n"
994 >>> t1.runstring(common, "common")
996 >>> t2.runstring(common, "common")
999 *** Tester.merge: 'common' in both testers; summing outcomes.
1001 3 items passed all tests:
1003 2 tests in t1example
1004 2 tests in t2example
1006 6 passed and 0 failed.
1013 for name, (f, t)
in other.name2ft.items():
1015 print "*** Tester.merge: '" + name +
"' in both" \
1016 " testers; summing outcomes."
1022 def __record_outcome(self, name, f, t):
1023 if self.name2ft.has_key(name):
1024 print "*** Warning: '" + name +
"' was tested before;", \
1031 def __runone(self, target, name):
1033 i = name.rindex(
".")
1034 prefix, base = name[:i], name[i+1:]
1036 prefix, base =
"", base
1039 return self.
rundoc(target, name)
1043 def testmod(m, name=None, globs=None, verbose=None, isprivate=None,
1045 """m, name=None, globs=None, verbose=None, isprivate=None, report=1
1047 Test examples in docstrings in functions and classes reachable from
1048 module m, starting with m.__doc__. Private names are skipped.
1050 Also test examples reachable from dict m.__test__ if it exists and is
1051 not None. m.__dict__ maps names to functions, classes and strings;
1052 function and class docstrings are tested even if the name is private;
1053 strings are tested directly, as if they were docstrings.
1055 Return (#failures, #tests).
1057 See doctest.__doc__ for an overview.
1059 Optional keyword arg "name" gives the name of the module; by default
1062 Optional keyword arg "globs" gives a dict to be used as the globals
1063 when executing examples; by default, use m.__dict__. A copy of this
1064 dict is actually used for each docstring, so that each docstring's
1065 examples start with a clean slate.
1067 Optional keyword arg "verbose" prints lots of stuff if true, prints
1068 only failures if false; by default, it's true iff "-v" is in sys.argv.
1070 Optional keyword arg "isprivate" specifies a function used to
1071 determine whether a name is private. The default function is
1072 doctest.is_private; see its docs for details.
1074 Optional keyword arg "report" prints a summary at the end when true,
1075 else prints nothing at the end. In verbose mode, the summary is
1076 detailed, else very brief (in fact, empty if all tests passed).
1078 Advanced tomfoolery: testmod runs methods of a local instance of
1079 class doctest.Tester, then merges the results into (or creates)
1080 global Tester instance doctest.master. Methods of doctest.master
1081 can be called directly too, if you want to do something unusual.
1082 Passing report=0 to testmod is especially useful then, to delay
1083 displaying a summary. Invoke doctest.master.summarize(verbose)
1084 when you're done fiddling.
1089 if not _ismodule(m):
1090 raise TypeError(
"testmod: module required; " + `m`)
1093 tester =
Tester(m, globs=globs, verbose=verbose, isprivate=isprivate)
1094 failures, tries = tester.rundoc(m, name)
1095 f, t = tester.rundict(m.__dict__, name, m)
1096 failures = failures + f
1098 if hasattr(m,
"__test__"):
1099 testdict = m.__test__
1101 if not hasattr(testdict,
"items"):
1102 raise TypeError(
"testmod: module.__test__ must support "
1103 ".items(); " + `testdict`)
1104 f, t = tester.run__test__(testdict, name +
".__test__")
1105 failures = failures + f
1112 master.merge(tester)
1113 return failures, tries
1117 A pointless class, for sanity-checking of docstring testing.
1123 >>> _TestClass(13).get() + _TestClass(-12).get()
1125 >>> hex(_TestClass(13).square().get())
1130 """val -> _TestClass object with associated value val.
1132 >>> t = _TestClass(123)
1140 """square() -> square TestClass's associated value
1142 >>> _TestClass(13).square().get()
1150 """get() -> return TestClass's associated value.
1152 >>> x = _TestClass(-42)
1159 __test__ = {
"_TestClass": _TestClass,
1161 Example of a string object, searched as-is.
1172 if __name__ ==
"__main__":