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.
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',
280 'DocTestTestFailure',
291 _isPS1
= re
.compile(r
"(\s*)" + re
.escape(PS1
)).match
292 _isPS2
= re
.compile(r
"(\s*)" + re
.escape(PS2
)).match
293 _isEmpty
= re
.compile(r
"\s*$").match
294 _isComment
= re
.compile(r
"\s*#").match
297 from types
import StringTypes
as _StringTypes
299 from inspect
import isclass
as _isclass
300 from inspect
import isfunction
as _isfunction
301 from inspect
import ismodule
as _ismodule
302 from inspect
import classify_class_attrs
as _classify_class_attrs
305 DONT_ACCEPT_TRUE_FOR_1
= 1 << 0
307 # Extract interactive examples from a string. Return a list of triples,
308 # (source, outcome, lineno). "source" is the source code, and ends
309 # with a newline iff the source spans more than one line. "outcome" is
310 # the expected output if any, else an empty string. When not empty,
311 # outcome always ends with a newline. "lineno" is the line number,
312 # 0-based wrt the start of the string, of the first source line.
314 def _extract_examples(s
):
315 isPS1
, isPS2
= _isPS1
, _isPS2
316 isEmpty
, isComment
= _isEmpty
, _isComment
318 lines
= s
.split("\n")
326 j
= m
.end(0) # beyond the prompt
327 if isEmpty(line
, j
) or isComment(line
, j
):
328 # a bare prompt or comment -- not interesting
332 raise ValueError("line " + `lineno`
+ " of docstring lacks "
333 "blank after " + PS1
+ ": " + line
)
336 nblanks
= len(blanks
)
337 # suck up this and following PS2 lines
340 source
.append(line
[j
:])
344 if m
.group(1) != blanks
:
345 raise ValueError("inconsistent leading whitespace "
346 "in line " + `i`
+ " of docstring: " + line
)
353 # get rid of useless null line from trailing empty "..."
356 source
= "\n".join(source
) + "\n"
358 if isPS1(line
) or isEmpty(line
):
363 if line
[:nblanks
] != blanks
:
364 raise ValueError("inconsistent leading whitespace "
365 "in line " + `i`
+ " of docstring: " + line
)
366 expect
.append(line
[nblanks
:])
369 if isPS1(line
) or isEmpty(line
):
371 expect
= "\n".join(expect
) + "\n"
372 examples
.append( (source
, expect
, lineno
) )
375 # Capture stdout when running examples.
383 guts
= "".join(self
.buf
)
384 # If anything at all was written, make sure there's a trailing
385 # newline. There's no way for the expected output to indicate
386 # that a trailing newline is missing.
387 if guts
and not guts
.endswith("\n"):
389 # Prevent softspace from screwing up the next test case, in
390 # case they used print with a trailing comma in an example.
391 if hasattr(self
, "softspace"):
396 if hasattr(self
, "softspace"):
399 # JPython calls flush
402 # Display some tag-and-msg pairs nicely, keeping the tag and its msg
403 # on the same line when that makes sense.
405 def _tag_out(printer
, *tag_msg_pairs
):
406 for tag
, msg
in tag_msg_pairs
:
408 msg_has_nl
= msg
[-1:] == "\n"
409 msg_has_two_nl
= msg_has_nl
and \
410 msg
.find("\n") < len(msg
) - 1
411 if len(tag
) + len(msg
) < 76 and not msg_has_two_nl
:
419 # Run list of examples, in context globs. "out" can be used to display
420 # stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
421 # that captures the examples' std output. Return (#failures, #tries).
423 def _run_examples_inner(out
, fakeout
, examples
, globs
, verbose
, name
,
424 compileflags
, optionflags
):
425 import sys
, traceback
426 OK
, BOOM
, FAIL
= range(3)
430 for source
, want
, lineno
in examples
:
432 _tag_out(out
, ("Trying", source
),
433 ("Expecting", want
or NADA
))
436 exec compile(source
, "<string>", "single",
437 compileflags
, 1) in globs
440 except KeyboardInterrupt:
443 # See whether the exception was expected.
444 if want
.find("Traceback (innermost last):\n") == 0 or \
445 want
.find("Traceback (most recent call last):\n") == 0:
446 # Only compare exception type and value - the rest of
447 # the traceback isn't necessary.
448 want
= want
.split('\n')[-2] + '\n'
449 exc_type
, exc_val
= sys
.exc_info()[:2]
450 got
= traceback
.format_exception_only(exc_type
, exc_val
)[-1]
453 # unexpected exception
455 traceback
.print_exc(file=stderr
)
460 (not (optionflags
& DONT_ACCEPT_TRUE_FOR_1
) and
461 (got
, want
) in (("True\n", "1\n"), ("False\n", "0\n"))
469 assert state
in (FAIL
, BOOM
)
470 failures
= failures
+ 1
472 _tag_out(out
, ("Failure in example", source
))
473 out("from line #" + `lineno`
+ " of " + name
+ "\n")
475 _tag_out(out
, ("Expected", want
or NADA
), ("Got", got
))
478 _tag_out(out
, ("Exception raised", stderr
.get()))
480 return failures
, len(examples
)
482 # Get the future-flags associated with the future features that have been
483 # imported into globs.
485 def _extract_future_flags(globs
):
487 for fname
in __future__
.all_feature_names
:
488 feature
= globs
.get(fname
, None)
489 if feature
is getattr(__future__
, fname
):
490 flags |
= feature
.compiler_flag
493 # Run list of examples, in a shallow copy of context (dict) globs.
494 # Return (#failures, #tries).
496 def _run_examples(examples
, globs
, verbose
, name
, compileflags
,
502 sys
.stdout
= fakeout
= _SpoofOut()
503 x
= _run_examples_inner(saveout
.write
, fakeout
, examples
,
504 globs
, verbose
, name
, compileflags
,
508 # While Python gc can clean up most cycles on its own, it doesn't
509 # chase frame objects. This is especially irksome when running
510 # generator tests that raise exceptions, because a named generator-
511 # iterator gets an entry in globs, and the generator-iterator
512 # object's frame's traceback info points back to globs. This is
513 # easy to break just by clearing the namespace. This can also
514 # help to break other kinds of cycles, and even for cycles that
515 # gc can break itself it's better to break them ASAP.
519 def run_docstring_examples(f
, globs
, verbose
=0, name
="NoName",
520 compileflags
=None, optionflags
=0):
521 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
523 Use (a shallow copy of) dict globs as the globals for execution.
524 Return (#failures, #tries).
526 If optional arg verbose is true, print stuff even if there are no
528 Use string name in failure msgs.
534 # docstring empty or None
536 # just in case CT invents a doc object that has to be forced
537 # to look like a string <0.9 wink>
539 except KeyboardInterrupt:
544 e
= _extract_examples(doc
)
547 if compileflags
is None:
548 compileflags
= _extract_future_flags(globs
)
549 return _run_examples(e
, globs
, verbose
, name
, compileflags
, optionflags
)
551 def is_private(prefix
, base
):
552 """prefix, base -> true iff name prefix + "." + base is "private".
554 Prefix may be an empty string, and base does not contain a period.
555 Prefix is ignored (although functions you write conforming to this
556 protocol may make use of it).
557 Return true iff base begins with an (at least one) underscore, but
558 does not both begin and end with (at least) two underscores.
560 >>> is_private("a.b", "my_func")
562 >>> is_private("____", "_my_func")
564 >>> is_private("someclass", "__init__")
566 >>> is_private("sometypo", "__init_")
568 >>> is_private("x.y.z", "_")
570 >>> is_private("_x.y.z", "__")
572 >>> is_private("", "") # senseless but consistent
576 return base
[:1] == "_" and not base
[:2] == "__" == base
[-2:]
578 # Determine if a class of function was defined in the given module.
580 def _from_module(module
, object):
581 if _isfunction(object):
582 return module
.__dict
__ is object.func_globals
584 return module
.__name
__ == object.__module
__
585 raise ValueError("object must be a class or function")
588 """Class Tester -- runs docstring examples and accumulates stats.
590 In normal use, function doctest.testmod() hides all this from you,
591 so use that if you can. Create your own instances of Tester to do
596 Search string s for examples to run; use name for logging.
597 Return (#failures, #tries).
599 rundoc(object, name=None)
600 Search object.__doc__ for examples to run; use name (or
601 object.__name__) for logging. Return (#failures, #tries).
603 rundict(d, name, module=None)
604 Search for examples in docstrings in all of d.values(); use name
605 for logging. Exclude functions and classes not defined in module
606 if specified. Return (#failures, #tries).
609 Treat dict d like module.__test__. Return (#failures, #tries).
611 summarize(verbose=None)
612 Display summary of testing results, to stdout. Return
616 Merge in the test results from Tester instance "other".
618 >>> from doctest import Tester
619 >>> t = Tester(globs={'x': 42}, verbose=0)
625 *****************************************************************
626 Failure in example: print x
631 >>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
634 *****************************************************************
635 1 items had failures:
637 ***Test Failed*** 1 failures.
639 >>> t.summarize(verbose=1)
640 1 items passed all tests:
642 *****************************************************************
643 1 items had failures:
646 3 passed and 1 failed.
647 ***Test Failed*** 1 failures.
652 def __init__(self
, mod
=None, globs
=None, verbose
=None,
653 isprivate
=None, optionflags
=0):
654 """mod=None, globs=None, verbose=None, isprivate=None,
657 See doctest.__doc__ for an overview.
659 Optional keyword arg "mod" is a module, whose globals are used for
660 executing examples. If not specified, globs must be specified.
662 Optional keyword arg "globs" gives a dict to be used as the globals
663 when executing examples; if not specified, use the globals from
666 In either case, a copy of the dict is used for each docstring
669 Optional keyword arg "verbose" prints lots of stuff if true, only
670 failures if false; by default, it's true iff "-v" is in sys.argv.
672 Optional keyword arg "isprivate" specifies a function used to determine
673 whether a name is private. The default function is doctest.is_private;
674 see its docs for details.
676 See doctest.testmod docs for the meaning of optionflags.
679 if mod
is None and globs
is None:
680 raise TypeError("Tester.__init__: must specify mod or globs")
681 if mod
is not None and not _ismodule(mod
):
682 raise TypeError("Tester.__init__: mod must be a module; " +
690 verbose
= "-v" in sys
.argv
691 self
.verbose
= verbose
693 if isprivate
is None:
694 isprivate
= is_private
695 self
.isprivate
= isprivate
697 self
.optionflags
= optionflags
699 self
.name2ft
= {} # map name to (#failures, #trials) pair
701 self
.compileflags
= _extract_future_flags(globs
)
703 def runstring(self
, s
, name
):
705 s, name -> search string s for examples to run, logging as name.
707 Use string name as the key for logging the outcome.
708 Return (#failures, #examples).
710 >>> t = Tester(globs={}, verbose=1)
712 ... # just an example
717 >>> t.runstring(test, "Example")
718 Running string Example
725 0 of 2 examples failed in string Example
730 print "Running string", name
732 e
= _extract_examples(s
)
734 f
, t
= _run_examples(e
, self
.globs
, self
.verbose
, name
,
735 self
.compileflags
, self
.optionflags
)
737 print f
, "of", t
, "examples failed in string", name
738 self
.__record
_outcome
(name
, f
, t
)
741 def rundoc(self
, object, name
=None):
743 object, name=None -> search object.__doc__ for examples to run.
745 Use optional string name as the key for logging the outcome;
746 by default use object.__name__.
747 Return (#failures, #examples).
748 If object is a class object, search recursively for method
750 object.__doc__ is examined regardless of name, but if object is
751 a class, whether private names reached from object are searched
752 depends on the constructor's "isprivate" argument.
754 >>> t = Tester(globs={}, verbose=0)
756 ... '''Trivial docstring example.
757 ... >>> assert 2 == 2
761 >>> t.rundoc(_f) # expect 0 failures in 1 example
767 name
= object.__name
__
768 except AttributeError:
769 raise ValueError("Tester.rundoc: name must be given "
770 "when object.__name__ doesn't exist; " + `
object`
)
772 print "Running", name
+ ".__doc__"
773 f
, t
= run_docstring_examples(object, self
.globs
, self
.verbose
, name
,
774 self
.compileflags
, self
.optionflags
)
776 print f
, "of", t
, "examples failed in", name
+ ".__doc__"
777 self
.__record
_outcome
(name
, f
, t
)
779 # In 2.2, class and static methods complicate life. Build
780 # a dict "that works", by hook or by crook.
782 for tag
, kind
, homecls
, value
in _classify_class_attrs(object):
784 if homecls
is not object:
785 # Only look at names defined immediately by the class.
788 elif self
.isprivate(name
, tag
):
791 elif kind
== "method":
792 # value is already a function
795 elif kind
== "static method":
796 # value isn't a function, but getattr reveals one
797 d
[tag
] = getattr(object, tag
)
799 elif kind
== "class method":
800 # Hmm. A classmethod object doesn't seem to reveal
801 # enough. But getattr turns it into a bound method,
802 # and from there .im_func retrieves the underlying
804 d
[tag
] = getattr(object, tag
).im_func
806 elif kind
== "property":
807 # The methods implementing the property have their
808 # own docstrings -- but the property may have one too.
809 if value
.__doc
__ is not None:
810 d
[tag
] = str(value
.__doc
__)
813 # Grab nested classes.
818 raise ValueError("teach doctest about %r" % kind
)
820 f2
, t2
= self
.run__test__(d
, name
)
826 def rundict(self
, d
, name
, module
=None):
828 d, name, module=None -> search for docstring examples in d.values().
830 For k, v in d.items() such that v is a function or class,
831 do self.rundoc(v, name + "." + k). Whether this includes
832 objects with private names depends on the constructor's
833 "isprivate" argument. If module is specified, functions and
834 classes that are not defined in module are excluded.
835 Return aggregate (#failures, #examples).
837 Build and populate two modules with sample functions to test that
838 exclusion of external functions and classes works.
841 >>> m1 = new.module('_m1')
842 >>> m2 = new.module('_m2')
845 ... '''>>> assert 1 == 1
848 ... '''>>> assert 2 != 1
851 ... '''>>> assert 2 > 1
854 ... '''>>> assert 1 < 2
857 >>> exec test_data in m1.__dict__
858 >>> exec test_data in m2.__dict__
859 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
861 Tests that objects outside m1 are excluded:
863 >>> t = Tester(globs={}, verbose=0)
864 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
867 Again, but with a custom isprivate function allowing _f:
869 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
870 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
873 And once more, not excluding stuff outside m1:
875 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
876 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
879 The exclusion of objects from outside the designated module is
880 meant to be invoked automagically by testmod.
887 if not hasattr(d
, "items"):
888 raise TypeError("Tester.rundict: d must support .items(); " +
891 # Run the tests by alpha order of names, for consistency in
892 # verbose-mode output.
895 for thisname
in names
:
897 if _isfunction(value
) or _isclass(value
):
898 if module
and not _from_module(module
, value
):
900 f2
, t2
= self
.__runone
(value
, name
+ "." + thisname
)
905 def run__test__(self
, d
, name
):
906 """d, name -> Treat dict d like module.__test__.
908 Return (#failures, #tries).
909 See testmod.__doc__ for details.
914 savepvt
= self
.isprivate
916 self
.isprivate
= lambda *args
: 0
917 # Run the tests by alpha order of names, for consistency in
918 # verbose-mode output.
923 thisname
= prefix
+ k
924 if type(v
) in _StringTypes
:
925 f
, t
= self
.runstring(v
, thisname
)
926 elif _isfunction(v
) or _isclass(v
):
927 f
, t
= self
.rundoc(v
, thisname
)
929 raise TypeError("Tester.run__test__: values in "
930 "dict must be strings, functions "
931 "or classes; " + `v`
)
932 failures
= failures
+ f
935 self
.isprivate
= savepvt
936 return failures
, tries
938 def summarize(self
, verbose
=None):
940 verbose=None -> summarize results, return (#failures, #tests).
942 Print summary of test results to stdout.
943 Optional arg 'verbose' controls how wordy this is. By
944 default, use the verbose setting established by the
949 verbose
= self
.verbose
954 for x
in self
.name2ft
.items():
962 passed
.append( (name
, t
) )
967 print len(notests
), "items had no tests:"
969 for thing
in notests
:
972 print len(passed
), "items passed all tests:"
974 for thing
, count
in passed
:
975 print " %3d tests in %s" % (count
, thing
)
978 print len(failed
), "items had failures:"
980 for thing
, (f
, t
) in failed
:
981 print " %3d of %3d in %s" % (f
, t
, thing
)
983 print totalt
, "tests in", len(self
.name2ft
), "items."
984 print totalt
- totalf
, "passed and", totalf
, "failed."
986 print "***Test Failed***", totalf
, "failures."
989 return totalf
, totalt
991 def merge(self
, other
):
993 other -> merge in test results from the other Tester instance.
995 If self and other both have a test result for something
996 with the same name, the (#failures, #tests) results are
997 summed, and a warning is printed to stdout.
999 >>> from doctest import Tester
1000 >>> t1 = Tester(globs={}, verbose=0)
1001 >>> t1.runstring('''
1005 ... ''', "t1example")
1008 >>> t2 = Tester(globs={}, verbose=0)
1009 >>> t2.runstring('''
1013 ... ''', "t2example")
1015 >>> common = ">>> assert 1 + 2 == 3\\n"
1016 >>> t1.runstring(common, "common")
1018 >>> t2.runstring(common, "common")
1021 *** Tester.merge: 'common' in both testers; summing outcomes.
1023 3 items passed all tests:
1025 2 tests in t1example
1026 2 tests in t2example
1028 6 passed and 0 failed.
1035 for name
, (f
, t
) in other
.name2ft
.items():
1037 print "*** Tester.merge: '" + name
+ "' in both" \
1038 " testers; summing outcomes."
1044 def __record_outcome(self
, name
, f
, t
):
1045 if name
in self
.name2ft
:
1046 print "*** Warning: '" + name
+ "' was tested before;", \
1048 f2
, t2
= self
.name2ft
[name
]
1051 self
.name2ft
[name
] = f
, t
1053 def __runone(self
, target
, name
):
1055 i
= name
.rindex(".")
1056 prefix
, base
= name
[:i
], name
[i
+1:]
1058 prefix
, base
= "", base
1059 if self
.isprivate(prefix
, base
):
1061 return self
.rundoc(target
, name
)
1065 def testmod(m
=None, name
=None, globs
=None, verbose
=None, isprivate
=None,
1066 report
=True, optionflags
=0):
1067 """m=None, name=None, globs=None, verbose=None, isprivate=None,
1068 report=True, optionflags=0
1070 Test examples in docstrings in functions and classes reachable
1071 from module m (or the current module if m is not supplied), starting
1072 with m.__doc__. Private names are skipped.
1074 Also test examples reachable from dict m.__test__ if it exists and is
1075 not None. m.__dict__ maps names to functions, classes and strings;
1076 function and class docstrings are tested even if the name is private;
1077 strings are tested directly, as if they were docstrings.
1079 Return (#failures, #tests).
1081 See doctest.__doc__ for an overview.
1083 Optional keyword arg "name" gives the name of the module; by default
1086 Optional keyword arg "globs" gives a dict to be used as the globals
1087 when executing examples; by default, use m.__dict__. A copy of this
1088 dict is actually used for each docstring, so that each docstring's
1089 examples start with a clean slate.
1091 Optional keyword arg "verbose" prints lots of stuff if true, prints
1092 only failures if false; by default, it's true iff "-v" is in sys.argv.
1094 Optional keyword arg "isprivate" specifies a function used to
1095 determine whether a name is private. The default function is
1096 doctest.is_private; see its docs for details.
1098 Optional keyword arg "report" prints a summary at the end when true,
1099 else prints nothing at the end. In verbose mode, the summary is
1100 detailed, else very brief (in fact, empty if all tests passed).
1102 Optional keyword arg "optionflags" or's together module constants,
1103 and defaults to 0. This is new in 2.3. Possible values:
1105 DONT_ACCEPT_TRUE_FOR_1
1106 By default, if an expected output block contains just "1",
1107 an actual output block containing just "True" is considered
1108 to be a match, and similarly for "0" versus "False". When
1109 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1112 Advanced tomfoolery: testmod runs methods of a local instance of
1113 class doctest.Tester, then merges the results into (or creates)
1114 global Tester instance doctest.master. Methods of doctest.master
1115 can be called directly too, if you want to do something unusual.
1116 Passing report=0 to testmod is especially useful then, to delay
1117 displaying a summary. Invoke doctest.master.summarize(verbose)
1118 when you're done fiddling.
1125 # DWA - m will still be None if this wasn't invoked from the command
1126 # line, in which case the following TypeError is about as good an error
1127 # as we should expect
1128 m
= sys
.modules
.get('__main__')
1130 if not _ismodule(m
):
1131 raise TypeError("testmod: module required; " + `m`
)
1134 tester
= Tester(m
, globs
=globs
, verbose
=verbose
, isprivate
=isprivate
,
1135 optionflags
=optionflags
)
1136 failures
, tries
= tester
.rundoc(m
, name
)
1137 f
, t
= tester
.rundict(m
.__dict
__, name
, m
)
1140 if hasattr(m
, "__test__"):
1141 testdict
= m
.__test
__
1143 if not hasattr(testdict
, "items"):
1144 raise TypeError("testmod: module.__test__ must support "
1145 ".items(); " + `testdict`
)
1146 f
, t
= tester
.run__test__(testdict
, name
+ ".__test__")
1154 master
.merge(tester
)
1155 return failures
, tries
1157 ###########################################################################
1158 # Various doctest extensions, to make using doctest with unittest
1159 # easier, and to help debugging when a doctest goes wrong. Original
1160 # code by Jim Fulton.
1164 # If module is None, return the calling module (the module that called
1165 # the routine that called _normalize_module -- this normally won't be
1166 # doctest!). If module is a string, it should be the (possibly dotted)
1167 # name of a module, and the (rightmost) module object is returned. Else
1168 # module is returned untouched; the intent appears to be that module is
1169 # already a module object in this case (although this isn't checked).
1171 def _normalize_module(module
):
1175 # Get our caller's caller's module.
1176 module
= sys
._getframe
(2).f_globals
['__name__']
1177 module
= sys
.modules
[module
]
1179 elif isinstance(module
, (str, unicode)):
1180 # The ["*"] at the end is a mostly meaningless incantation with
1181 # a crucial property: if, e.g., module is 'a.b.c', it convinces
1182 # __import__ to return c instead of a.
1183 module
= __import__(module
, globals(), locals(), ["*"])
1187 # tests is a list of (testname, docstring, filename, lineno) tuples.
1188 # If object has a __doc__ attr, and the __doc__ attr looks like it
1189 # contains a doctest (specifically, if it contains an instance of '>>>'),
1191 # prefix + name, object.__doc__, filename, lineno
1192 # is appended to tests. Else tests is left alone.
1193 # There is no return value.
1195 def _get_doctest(name
, object, tests
, prefix
, filename
='', lineno
=''):
1196 doc
= getattr(object, '__doc__', '')
1197 if isinstance(doc
, basestring
) and '>>>' in doc
:
1198 tests
.append((prefix
+ name
, doc
, filename
, lineno
))
1200 # tests is a list of (testname, docstring, filename, lineno) tuples.
1201 # docstrings containing doctests are appended to tests (if any are found).
1202 # items is a dict, like a module or class dict, mapping strings to objects.
1203 # mdict is the global dict of a "home" module -- only objects belonging
1204 # to this module are searched for docstrings. module is the module to
1205 # which mdict belongs.
1206 # prefix is a string to be prepended to an object's name when adding a
1208 # The objects (values) in items are examined (recursively), and doctests
1209 # belonging to functions and classes in the home module are appended to
1211 # minlineno is a gimmick to try to guess the file-relative line number
1212 # at which a doctest probably begins.
1214 def _extract_doctests(items
, module
, mdict
, tests
, prefix
, minlineno
=0):
1216 for name
, object in items
:
1217 # Only interested in named objects.
1218 if not hasattr(object, '__name__'):
1221 elif hasattr(object, 'func_globals'):
1222 # Looks like a function.
1223 if object.func_globals
is not mdict
:
1224 # Non-local function.
1226 code
= getattr(object, 'func_code', None)
1227 filename
= getattr(code
, 'co_filename', '')
1228 lineno
= getattr(code
, 'co_firstlineno', -1) + 1
1230 minlineno
= min(lineno
, minlineno
)
1233 _get_doctest(name
, object, tests
, prefix
, filename
, lineno
)
1235 elif hasattr(object, "__module__"):
1236 # Maybe a class-like thing, in which case we care.
1237 if object.__module
__ != module
.__name
__:
1238 # Not the same module.
1240 if not (hasattr(object, '__dict__')
1241 and hasattr(object, '__bases__')):
1245 lineno
= _extract_doctests(object.__dict
__.items(),
1249 prefix
+ name
+ ".")
1250 # XXX "-3" is unclear.
1251 _get_doctest(name
, object, tests
, prefix
,
1252 lineno
="%s (or above)" % (lineno
- 3))
1256 # Find all the doctests belonging to the module object.
1258 # (testname, docstring, filename, lineno)
1261 def _find_tests(module
, prefix
=None):
1263 prefix
= module
.__name
__
1264 mdict
= module
.__dict
__
1266 # Get the module-level doctest (if any).
1267 _get_doctest(prefix
, module
, tests
, '', lineno
="1 (or above)")
1268 # Recursively search the module __dict__ for doctests.
1271 _extract_doctests(mdict
.items(), module
, mdict
, tests
, prefix
)
1276 # A function passed to unittest, for unittest to drive.
1277 # tester is doctest Tester instance. doc is the docstring whose
1278 # doctests are to be run.
1280 def _utest(tester
, name
, doc
, filename
, lineno
):
1282 from StringIO
import StringIO
1285 sys
.stdout
= new
= StringIO()
1287 failures
, tries
= tester
.runstring(doc
, name
)
1292 msg
= new
.getvalue()
1293 lname
= '.'.join(name
.split('.')[-1:])
1295 lineno
= "0 (don't know line number)"
1296 # Don't change this format! It was designed so that Emacs can
1297 # parse it naturally.
1298 raise DocTestTestFailure('Failed doctest test for %s\n'
1299 ' File "%s", line %s, in %s\n\n%s' %
1300 (name
, filename
, lineno
, lname
, msg
))
1302 class DocTestTestFailure(Exception):
1303 """A doctest test failed"""
1305 def DocTestSuite(module
=None):
1306 """Convert doctest tests for a module to a unittest TestSuite.
1308 The returned TestSuite is to be run by the unittest framework, and
1309 runs each doctest in the module. If any of the doctests fail,
1310 then the synthesized unit test fails, and an error is raised showing
1311 the name of the file containing the test and a (sometimes approximate)
1314 The optional module argument provides the module to be tested. It
1315 can be a module object or a (possibly dotted) module name. If not
1316 specified, the module calling DocTestSuite() is used.
1318 Example (although note that unittest supplies many ways to use the
1319 TestSuite returned; see the unittest docs):
1323 import my_module_with_doctests
1325 suite = doctest.DocTestSuite(my_module_with_doctests)
1326 runner = unittest.TextTestRunner()
1332 module
= _normalize_module(module
)
1333 tests
= _find_tests(module
)
1335 raise ValueError(module
, "has no tests")
1338 suite
= unittest
.TestSuite()
1339 tester
= Tester(module
)
1340 for name
, doc
, filename
, lineno
in tests
:
1342 filename
= module
.__file
__
1343 if filename
.endswith(".pyc"):
1344 filename
= filename
[:-1]
1345 elif filename
.endswith(".pyo"):
1346 filename
= filename
[:-1]
1347 def runit(name
=name
, doc
=doc
, filename
=filename
, lineno
=lineno
):
1348 _utest(tester
, name
, doc
, filename
, lineno
)
1349 suite
.addTest(unittest
.FunctionTestCase(
1351 description
="doctest of " + name
))
1354 # Debugging support.
1356 def _expect(expect
):
1357 # Return the expected output (if any), formatted as a Python
1360 expect
= "\n# ".join(expect
.split("\n"))
1361 expect
= "\n# Expect:\n# %s" % expect
1364 def testsource(module
, name
):
1365 """Extract the doctest examples from a docstring.
1367 Provide the module (or dotted name of the module) containing the
1368 tests to be extracted, and the name (within the module) of the object
1369 with the docstring containing the tests to be extracted.
1371 The doctest examples are returned as a string containing Python
1372 code. The expected output blocks in the examples are converted
1376 module
= _normalize_module(module
)
1377 tests
= _find_tests(module
, "")
1378 test
= [doc
for (tname
, doc
, dummy
, dummy
) in tests
1381 raise ValueError(name
, "not found in tests")
1383 examples
= [source
+ _expect(expect
)
1384 for source
, expect
, dummy
in _extract_examples(test
)]
1385 return '\n'.join(examples
)
1387 def debug(module
, name
):
1388 """Debug a single docstring containing doctests.
1390 Provide the module (or dotted name of the module) containing the
1391 docstring to be debugged, and the name (within the module) of the
1392 object with the docstring to be debugged.
1394 The doctest examples are extracted (see function testsource()),
1395 and written to a temp file. The Python debugger (pdb) is then
1396 invoked on that file.
1403 module
= _normalize_module(module
)
1404 testsrc
= testsource(module
, name
)
1405 srcfilename
= tempfile
.mktemp("doctestdebug.py")
1406 f
= file(srcfilename
, 'w')
1411 globs
.update(module
.__dict
__)
1413 # Note that %r is vital here. '%s' instead can, e.g., cause
1414 # backslashes to get treated as metacharacters on Windows.
1415 pdb
.run("execfile(%r)" % srcfilename
, globs
, globs
)
1417 os
.remove(srcfilename
)
1423 A pointless class, for sanity-checking of docstring testing.
1429 >>> _TestClass(13).get() + _TestClass(-12).get()
1431 >>> hex(_TestClass(13).square().get())
1435 def __init__(self
, val
):
1436 """val -> _TestClass object with associated value val.
1438 >>> t = _TestClass(123)
1446 """square() -> square TestClass's associated value
1448 >>> _TestClass(13).square().get()
1452 self
.val
= self
.val
** 2
1456 """get() -> return TestClass's associated value.
1458 >>> x = _TestClass(-42)
1465 __test__
= {"_TestClass": _TestClass
,
1467 Example of a string object, searched as-is.
1472 "bool-int equivalence": r
"""
1473 In 2.2, boolean expressions displayed
1474 0 or 1. By default, we still accept
1475 them. This can be disabled by passing
1476 DONT_ACCEPT_TRUE_FOR_1 to the new
1477 optionflags argument.
1491 return doctest
.testmod(doctest
)
1493 if __name__
== "__main__":