1
# Module doctest version 0.9.6
2
# Released to the public domain 16-Jan-2001,
3
# by Tim Peters (tim.one@home.com).
6
# 2001-02-13 fl: minor tweaks to make it run under both 1.5.2 and 2.0
8
# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
10
"""Module doctest -- a framework for running examples in docstrings.
14
In normal use, end each module M with:
17
import doctest, M # replace M with your module's name
18
return doctest.testmod(M) # ditto
20
if __name__ == "__main__":
23
Then running the module as a script will cause the examples in the
24
docstrings to get executed and verified:
28
This won't display anything unless an example fails, in which case the
29
failing example(s) and the cause(s) of the failure(s) are printed to stdout
30
(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
31
line of output is "Test failed.".
33
Run it with the -v switch instead:
37
and a detailed report of all examples tried is printed to stdout, along
38
with assorted summaries at the end.
40
You can force verbose mode by passing "verbose=1" to testmod, or prohibit
41
it by passing "verbose=0". In either of those cases, sys.argv is not
44
In any case, testmod returns a 2-tuple of ints (f, t), where f is the
45
number of docstring examples that failed and t is the total number of
46
docstring examples attempted.
49
WHICH DOCSTRINGS ARE EXAMINED?
53
+ f.__doc__ for all functions f in M.__dict__.values(), except those
56
+ C.__doc__ for all classes C in M.__dict__.values(), except those with
59
+ If M.__test__ exists and "is true", it must be a dict, and
60
each entry maps a (string) name to a function object, class object, or
61
string. Function and class object docstrings found from M.__test__
62
are searched even if the name is private, and strings are searched
63
directly as if they were docstrings. In output, a key K in M.__test__
65
<name of M>.__test__.K
67
Any classes found are recursively searched similarly, to test docstrings in
68
their contained methods and nested classes. Private names reached from M's
69
globals are skipped, but all names reached from M.__test__ are searched.
71
By default, a name is considered to be private if it begins with an
72
underscore (like "_my_func") but doesn't both begin and end with (at least)
73
two underscores (like "__init__"). You can change the default by passing
74
your own "isprivate" function to testmod.
76
If you want to test docstrings in objects with private names too, stuff
77
them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
78
own isprivate function to Tester's constructor, or call the rundoc method
79
of a Tester instance).
81
Warning: imports can cause trouble; e.g., if you do
83
from XYZ import XYZclass
85
then XYZclass is a name in M.__dict__ too, and doctest has no way to know
86
that XYZclass wasn't *defined* in M. So it may try to execute the examples
87
in XYZclass's docstring, and those in turn may require a different set of
88
globals to work correctly. I prefer to do "import *"- friendly imports,
92
_XYZclass = XYZ.XYZclass
97
from XYZ import XYZclass as _XYZclass
99
and then the leading underscore stops testmod from going nuts. You may
100
prefer the method in the next section.
103
WHAT'S THE EXECUTION CONTEXT?
105
By default, each time testmod finds a docstring to test, it uses a *copy*
106
of M's globals (so that running tests on a module doesn't change the
107
module's real globals, and so that one test in M can't leave behind crumbs
108
that accidentally allow another test to work). This means examples can
109
freely use any names defined at top-level in M. It also means that sloppy
110
imports (see above) can cause examples in external docstrings to use
111
globals inappropriate for them.
113
You can force use of your own dict as the execution context by passing
114
"globs=your_dict" to testmod instead. Presumably this would be a copy of
115
M.__dict__ merged with the globals from other imported modules.
118
WHAT IF I WANT TO TEST A WHOLE PACKAGE?
120
Piece o' cake, provided the modules do their testing from docstrings.
121
Here's the test.py I use for the world's most elaborate Rational/
122
floating-base-conversion pkg (which I'll distribute some day):
124
from Rational import Cvt
125
from Rational import Format
126
from Rational import machprec
127
from Rational import Rat
128
from Rational import Round
129
from Rational import utils
141
verbose = "-v" in sys.argv
143
doctest.testmod(mod, verbose=verbose, report=0)
144
doctest.master.summarize()
146
if __name__ == "__main__":
149
IOW, it just runs testmod on all the pkg modules. testmod remembers the
150
names and outcomes (# of failures, # of tries) for each item it's seen, and
151
passing "report=0" prevents it from printing a summary in verbose mode.
152
Instead, the summary is delayed until all modules have been tested, and
153
then "doctest.master.summarize()" forces the summary at the end.
155
So this is very nice in practice: each module can be tested individually
156
with almost no work beyond writing up docstring examples, and collections
157
of modules can be tested too as a unit with no more work than the above.
160
WHAT ABOUT EXCEPTIONS?
162
No problem, as long as the only output generated by the example is the
163
traceback itself. For example:
167
Traceback (innermost last):
168
File "<stdin>", line 1, in ?
169
IndexError: list index out of range
172
Note that only the exception type and value are compared (specifically,
173
only the last line in the traceback).
178
doctest.testmod() captures the testing policy I find most useful most
179
often. You may want other policies.
181
testmod() actually creates a local instance of class doctest.Tester, runs
182
appropriate methods of that class, and merges the results into global
183
Tester instance doctest.master.
185
You can create your own instances of doctest.Tester, and so build your own
186
policies, or even run methods of doctest.master directly. See
187
doctest.Tester.__doc__ for details.
190
SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
192
Oh ya. It's easy! In most cases a copy-and-paste of an interactive
193
console session works fine -- just make sure the leading whitespace is
194
rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
195
right, but doctest is not in the business of guessing what you think a tab
198
>>> # comments are ignored
214
Any expected output must immediately follow the final ">>>" or "..." line
215
containing the code, and the expected output (if any) extends to the next
216
">>>" or all-whitespace line. That's it.
220
+ Expected output cannot contain an all-whitespace line, since such a line
221
is taken to signal the end of expected output.
223
+ Output to stdout is captured, but not output to stderr (exception
224
tracebacks are captured via a different means).
226
+ If you continue a line via backslashing in an interactive session, or for
227
any other reason use a backslash, you need to double the backslash in the
228
docstring version. This is simply because you're in a string, and so the
229
backslash must be escaped for it to survive intact. Like:
233
... "es": # in the source code you'll see the doubled backslashes
237
The starting column doesn't matter:
244
and as many leading whitespace characters are stripped from the expected
245
output as appeared in the initial ">>>" line that triggered it.
247
If you execute this very file, the examples above will be found and
248
executed, leading to this output in verbose mode:
250
Running doctest.__doc__
256
Traceback (innermost last):
257
File "<stdin>", line 1, in ?
258
IndexError: list index out of range
278
... and a bunch more like that, with this summary at the end:
280
5 items had no tests:
281
doctest.Tester.__init__
282
doctest.Tester.run__test__
283
doctest.Tester.summarize
284
doctest.run_docstring_examples
286
12 items passed all tests:
288
6 tests in doctest.Tester
289
10 tests in doctest.Tester.merge
290
7 tests in doctest.Tester.rundict
291
3 tests in doctest.Tester.rundoc
292
3 tests in doctest.Tester.runstring
293
2 tests in doctest.__test__._TestClass
294
2 tests in doctest.__test__._TestClass.__init__
295
2 tests in doctest.__test__._TestClass.get
296
1 tests in doctest.__test__._TestClass.square
297
2 tests in doctest.__test__.string
298
7 tests in doctest.is_private
299
54 tests in 17 items.
300
54 passed and 0 failed.
305
# initial version posted
308
# cater to stinkin' tabs
309
# don't insist on a blank after PS2 prefix
310
# so trailing "... " line from a compound stmt no longer
311
# breaks if the file gets whitespace-trimmed
312
# better error msgs for inconsistent leading whitespace
314
# exposed the Tester class and added client methods
315
# plus docstring examples of their use (eww - head-twisting!)
316
# fixed logic error in reporting total # of tests & failures
317
# added __test__ support to testmod (a pale reflection of Christian
318
# Tismer's vision ...)
319
# removed the "deep" argument; fiddle __test__ instead
320
# simplified endcase logic for extracting tests, and running them.
321
# before, if no output was expected but some was produced
322
# anyway via an eval'ed result, the discrepancy wasn't caught
323
# made TestClass private and used __test__ to get at it
325
# speed _SpoofOut for long expected outputs
327
# throw out comments from examples, enabling use of the much simpler
328
# exec compile(... "single") ...
329
# for simulating the runtime; that barfs on comment-only lines
330
# used the traceback module to do a much better job of reporting
332
# run __doc__ values thru str(), "just in case"
333
# privateness of names now determined by an overridable "isprivate"
335
# by default a name now considered to be private iff it begins with
336
# an underscore but doesn't both begin & end with two of 'em; so
337
# e.g. Class.__init__ etc are searched now -- as they always
340
# added .flush stub to _SpoofOut (JPython buglet diagnosed by
342
# repaired ridiculous docs about backslashes in examples
343
# minor internal changes
344
# changed source to Unix line-end conventions
345
# moved __test__ logic into new Tester.run__test__ method
347
# report item name and line # in failing examples
349
# allow straightforward exceptions in examples - thanks to Mark Hammond!
351
# fiddling for changes in Python 2.0: some of the embedded docstring
352
# examples no longer worked *exactly* as advertised, due to minor
353
# language changes, and running doctest on itself pointed that out.
354
# Hard to think of a better example of why this is useful <wink>.
356
__version__ = 0, 9, 6
359
_FunctionType = types.FunctionType
360
_ClassType = types.ClassType
361
_ModuleType = types.ModuleType
362
_StringType = types.StringType
366
_string_find = string.find
367
_string_join = string.join
368
_string_split = string.split
369
_string_rindex = string.rindex
375
_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
376
_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
377
_isEmpty = re.compile(r"\s*$").match
378
_isComment = re.compile(r"\s*#").match
383
# Extract interactive examples from a string. Return a list of triples,
384
# (source, outcome, lineno). "source" is the source code, and ends
385
# with a newline iff the source spans more than one line. "outcome" is
386
# the expected output if any, else an empty string. When not empty,
387
# outcome always ends with a newline. "lineno" is the line number,
388
# 0-based wrt the start of the string, of the first source line.
390
def _extract_examples(s):
391
isPS1, isPS2 = _isPS1, _isPS2
392
isEmpty, isComment = _isEmpty, _isComment
394
lines = _string_split(s, "\n")
402
j = m.end(0) # beyond the prompt
403
if isEmpty(line, j) or isComment(line, j):
404
# a bare prompt or comment -- not interesting
408
raise ValueError("line " + `lineno` + " of docstring lacks "
409
"blank after " + PS1 + ": " + line)
412
nblanks = len(blanks)
413
# suck up this and following PS2 lines
416
source.append(line[j:])
420
if m.group(1) != blanks:
421
raise ValueError("inconsistent leading whitespace "
422
"in line " + `i` + " of docstring: " + line)
429
# get rid of useless null line from trailing empty "..."
432
source = _string_join(source, "\n") + "\n"
434
if isPS1(line) or isEmpty(line):
439
if line[:nblanks] != blanks:
440
raise ValueError("inconsistent leading whitespace "
441
"in line " + `i` + " of docstring: " + line)
442
expect.append(line[nblanks:])
445
if isPS1(line) or isEmpty(line):
447
expect = _string_join(expect, "\n") + "\n"
448
examples.append( (source, expect, lineno) )
451
# Capture stdout when running examples.
459
return _string_join(self.buf, "")
463
# JPython calls flush
466
# Display some tag-and-msg pairs nicely, keeping the tag and its msg
467
# on the same line when that makes sense.
469
def _tag_out(printer, *tag_msg_pairs):
470
for tag, msg in tag_msg_pairs:
472
msg_has_nl = msg[-1:] == "\n"
473
msg_has_two_nl = msg_has_nl and \
474
_string_find(msg, "\n") < len(msg) - 1
475
if len(tag) + len(msg) < 76 and not msg_has_two_nl:
483
# Run list of examples, in context globs. "out" can be used to display
484
# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
485
# that captures the examples' std output. Return (#failures, #tries).
487
def _run_examples_inner(out, fakeout, examples, globs, verbose, name):
488
import sys, traceback
489
OK, BOOM, FAIL = range(3)
493
for source, want, lineno in examples:
495
_tag_out(out, ("Trying", source),
496
("Expecting", want or NADA))
499
exec compile(source, "<string>", "single") in globs
503
# See whether the exception was expected.
504
if _string_find(want, "Traceback (innermost last):\n") == 0 or\
505
_string_find(want, "Traceback (most recent call last):\n") == 0:
506
# Only compare exception type and value - the rest of
507
# the traceback isn't necessary.
508
want = _string_split(want, '\n')[-2] + '\n'
509
exc_type, exc_val, exc_tb = sys.exc_info()
510
got = traceback.format_exception_only(exc_type, exc_val)[0]
513
# unexpected exception
515
traceback.print_exc(file=stderr)
525
assert state in (FAIL, BOOM)
526
failures = failures + 1
528
_tag_out(out, ("Failure in example", source))
529
out("from line #" + `lineno` + " of " + name + "\n")
531
_tag_out(out, ("Expected", want or NADA), ("Got", got))
534
_tag_out(out, ("Exception raised", stderr.get()))
536
return failures, len(examples)
538
# Run list of examples, in context globs. Return (#failures, #tries).
540
def _run_examples(examples, globs, verbose, name):
544
sys.stdout = fakeout = _SpoofOut()
545
x = _run_examples_inner(saveout.write, fakeout, examples,
546
globs, verbose, name)
551
def run_docstring_examples(f, globs, verbose=0, name="NoName"):
552
"""f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
554
Use dict globs as the globals for execution.
555
Return (#failures, #tries).
557
If optional arg verbose is true, print stuff even if there are no
559
Use string name in failure msgs.
565
# docstring empty or None
567
# just in case CT invents a doc object that has to be forced
568
# to look like a string <0.9 wink>
573
e = _extract_examples(doc)
576
return _run_examples(e, globs, verbose, name)
578
def is_private(prefix, base):
579
"""prefix, base -> true iff name prefix + "." + base is "private".
581
Prefix may be an empty string, and base does not contain a period.
582
Prefix is ignored (although functions you write conforming to this
583
protocol may make use of it).
584
Return true iff base begins with an (at least one) underscore, but
585
does not both begin and end with (at least) two underscores.
587
>>> is_private("a.b", "my_func")
589
>>> is_private("____", "_my_func")
591
>>> is_private("someclass", "__init__")
593
>>> is_private("sometypo", "__init_")
595
>>> is_private("x.y.z", "_")
597
>>> is_private("_x.y.z", "__")
599
>>> is_private("", "") # senseless but consistent
603
return base[:1] == "_" and not base[:2] == "__" == base[-2:]
606
"""Class Tester -- runs docstring examples and accumulates stats.
608
In normal use, function doctest.testmod() hides all this from you,
609
so use that if you can. Create your own instances of Tester to do
614
Search string s for examples to run; use name for logging.
615
Return (#failures, #tries).
617
rundoc(object, name=None)
618
Search object.__doc__ for examples to run; use name (or
619
object.__name__) for logging. Return (#failures, #tries).
622
Search for examples in docstrings in all of d.values(); use name
623
for logging. Return (#failures, #tries).
626
Treat dict d like module.__test__. Return (#failures, #tries).
628
summarize(verbose=None)
629
Display summary of testing results, to stdout. Return
633
Merge in the test results from Tester instance "other".
635
>>> from doctest import Tester
636
>>> t = Tester(globs={'x': 42}, verbose=0)
642
*****************************************************************
643
Failure in example: print x
648
>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
651
1 items had failures:
653
***Test Failed*** 1 failures.
655
>>> t.summarize(verbose=1)
656
1 items passed all tests:
658
1 items had failures:
661
3 passed and 1 failed.
662
***Test Failed*** 1 failures.
667
def __init__(self, mod=None, globs=None, verbose=None,
669
"""mod=None, globs=None, verbose=None, isprivate=None
671
See doctest.__doc__ for an overview.
673
Optional keyword arg "mod" is a module, whose globals are used for
674
executing examples. If not specified, globs must be specified.
676
Optional keyword arg "globs" gives a dict to be used as the globals
677
when executing examples; if not specified, use the globals from
680
In either case, a copy of the dict is used for each docstring
683
Optional keyword arg "verbose" prints lots of stuff if true, only
684
failures if false; by default, it's true iff "-v" is in sys.argv.
686
Optional keyword arg "isprivate" specifies a function used to determine
687
whether a name is private. The default function is doctest.is_private;
688
see its docs for details.
691
if mod is None and globs is None:
692
raise TypeError("Tester.__init__: must specify mod or globs")
693
if mod is not None and type(mod) is not _ModuleType:
694
raise TypeError("Tester.__init__: mod must be a module; " +
702
verbose = "-v" in sys.argv
703
self.verbose = verbose
705
if isprivate is None:
706
isprivate = is_private
707
self.isprivate = isprivate
709
self.name2ft = {} # map name to (#failures, #trials) pair
711
def runstring(self, s, name):
713
s, name -> search string s for examples to run, logging as name.
715
Use string name as the key for logging the outcome.
716
Return (#failures, #examples).
718
>>> t = Tester(globs={}, verbose=1)
720
... # just an example
725
>>> t.runstring(test, "Example")
726
Running string Example
733
0 of 2 examples failed in string Example
738
print "Running string", name
740
e = _extract_examples(s)
742
f, t = _run_examples(e, self.globs.copy(), self.verbose, name)
744
print f, "of", t, "examples failed in string", name
745
self.__record_outcome(name, f, t)
748
def rundoc(self, object, name=None):
750
object, name=None -> search object.__doc__ for examples to run.
752
Use optional string name as the key for logging the outcome;
753
by default use object.__name__.
754
Return (#failures, #examples).
755
If object is a class object, search recursively for method
757
object.__doc__ is examined regardless of name, but if object is
758
a class, whether private names reached from object are searched
759
depends on the constructor's "isprivate" argument.
761
>>> t = Tester(globs={}, verbose=0)
763
... '''Trivial docstring example.
764
... >>> assert 2 == 2
768
>>> t.rundoc(_f) # expect 0 failures in 1 example
774
name = object.__name__
775
except AttributeError:
776
raise ValueError("Tester.rundoc: name must be given "
777
"when object.__name__ doesn't exist; " + `object`)
779
print "Running", name + ".__doc__"
780
f, t = run_docstring_examples(object, self.globs.copy(),
783
print f, "of", t, "examples failed in", name + ".__doc__"
784
self.__record_outcome(name, f, t)
785
if type(object) is _ClassType:
786
f2, t2 = self.rundict(object.__dict__, name)
791
def rundict(self, d, name):
793
d. name -> search for docstring examples in all of d.values().
795
For k, v in d.items() such that v is a function or class,
796
do self.rundoc(v, name + "." + k). Whether this includes
797
objects with private names depends on the constructor's
798
"isprivate" argument.
799
Return aggregate (#failures, #examples).
802
... '''>>> assert 1 == 1
805
... '''>>> assert 2 != 1
807
>>> d = {"_f": _f, "g": g}
808
>>> t = Tester(globs={}, verbose=0)
809
>>> t.rundict(d, "rundict_test") # _f is skipped
811
>>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
812
>>> t.rundict(d, "rundict_test_pvt") # both are searched
816
if not hasattr(d, "items"):
817
raise TypeError("Tester.rundict: d must support .items(); " +
820
for thisname, value in d.items():
821
if type(value) in (_FunctionType, _ClassType):
822
f2, t2 = self.__runone(value, name + "." + thisname)
827
def run__test__(self, d, name):
828
"""d, name -> Treat dict d like module.__test__.
830
Return (#failures, #tries).
831
See testmod.__doc__ for details.
836
savepvt = self.isprivate
838
self.isprivate = lambda *args: 0
839
for k, v in d.items():
840
thisname = prefix + k
841
if type(v) is _StringType:
842
f, t = self.runstring(v, thisname)
843
elif type(v) in (_FunctionType, _ClassType):
844
f, t = self.rundoc(v, thisname)
846
raise TypeError("Tester.run__test__: values in "
847
"dict must be strings, functions "
848
"or classes; " + `v`)
849
failures = failures + f
852
self.isprivate = savepvt
853
return failures, tries
855
def summarize(self, verbose=None):
857
verbose=None -> summarize results, return (#failures, #tests).
859
Print summary of test results to stdout.
860
Optional arg 'verbose' controls how wordy this is. By
861
default, use the verbose setting established by the
866
verbose = self.verbose
871
for x in self.name2ft.items():
879
passed.append( (name, t) )
884
print len(notests), "items had no tests:"
886
for thing in notests:
889
print len(passed), "items passed all tests:"
891
for thing, count in passed:
892
print " %3d tests in %s" % (count, thing)
894
print len(failed), "items had failures:"
896
for thing, (f, t) in failed:
897
print " %3d of %3d in %s" % (f, t, thing)
899
print totalt, "tests in", len(self.name2ft), "items."
900
print totalt - totalf, "passed and", totalf, "failed."
902
print "***Test Failed***", totalf, "failures."
905
return totalf, totalt
907
def merge(self, other):
909
other -> merge in test results from the other Tester instance.
911
If self and other both have a test result for something
912
with the same name, the (#failures, #tests) results are
913
summed, and a warning is printed to stdout.
915
>>> from doctest import Tester
916
>>> t1 = Tester(globs={}, verbose=0)
921
... ''', "t1example")
924
>>> t2 = Tester(globs={}, verbose=0)
929
... ''', "t2example")
931
>>> common = ">>> assert 1 + 2 == 3\\n"
932
>>> t1.runstring(common, "common")
934
>>> t2.runstring(common, "common")
937
*** Tester.merge: 'common' in both testers; summing outcomes.
939
3 items passed all tests:
944
6 passed and 0 failed.
951
for name, (f, t) in other.name2ft.items():
953
print "*** Tester.merge: '" + name + "' in both" \
954
" testers; summing outcomes."
960
def __record_outcome(self, name, f, t):
961
if self.name2ft.has_key(name):
962
print "*** Warning: '" + name + "' was tested before;", \
964
f2, t2 = self.name2ft[name]
967
self.name2ft[name] = f, t
969
def __runone(self, target, name):
971
i = _string_rindex(name, ".")
972
prefix, base = name[:i], name[i+1:]
974
prefix, base = "", base
975
if self.isprivate(prefix, base):
977
return self.rundoc(target, name)
981
def testmod(m, name=None, globs=None, verbose=None, isprivate=None,
983
"""m, name=None, globs=None, verbose=None, isprivate=None, report=1
985
Test examples in docstrings in functions and classes reachable from
986
module m, starting with m.__doc__. Private names are skipped.
988
Also test examples reachable from dict m.__test__ if it exists and is
989
not None. m.__dict__ maps names to functions, classes and strings;
990
function and class docstrings are tested even if the name is private;
991
strings are tested directly, as if they were docstrings.
993
Return (#failures, #tests).
995
See doctest.__doc__ for an overview.
997
Optional keyword arg "name" gives the name of the module; by default
1000
Optional keyword arg "globs" gives a dict to be used as the globals
1001
when executing examples; by default, use m.__dict__. A copy of this
1002
dict is actually used for each docstring, so that each docstring's
1003
examples start with a clean slate.
1005
Optional keyword arg "verbose" prints lots of stuff if true, prints
1006
only failures if false; by default, it's true iff "-v" is in sys.argv.
1008
Optional keyword arg "isprivate" specifies a function used to
1009
determine whether a name is private. The default function is
1010
doctest.is_private; see its docs for details.
1012
Optional keyword arg "report" prints a summary at the end when true,
1013
else prints nothing at the end. In verbose mode, the summary is
1014
detailed, else very brief (in fact, empty if all tests passed).
1016
Advanced tomfoolery: testmod runs methods of a local instance of
1017
class doctest.Tester, then merges the results into (or creates)
1018
global Tester instance doctest.master. Methods of doctest.master
1019
can be called directly too, if you want to do something unusual.
1020
Passing report=0 to testmod is especially useful then, to delay
1021
displaying a summary. Invoke doctest.master.summarize(verbose)
1022
when you're done fiddling.
1027
if type(m) is not _ModuleType:
1028
raise TypeError("testmod: module required; " + `m`)
1031
tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate)
1032
failures, tries = tester.rundoc(m, name)
1033
f, t = tester.rundict(m.__dict__, name)
1034
failures = failures + f
1036
if hasattr(m, "__test__"):
1037
testdict = m.__test__
1039
if not hasattr(testdict, "items"):
1040
raise TypeError("testmod: module.__test__ must support "
1041
".items(); " + `testdict`)
1042
f, t = tester.run__test__(testdict, name + ".__test__")
1043
failures = failures + f
1050
master.merge(tester)
1051
return failures, tries
1055
A pointless class, for sanity-checking of docstring testing.
1061
>>> _TestClass(13).get() + _TestClass(-12).get()
1063
>>> hex(_TestClass(13).square().get())
1067
def __init__(self, val):
1068
"""val -> _TestClass object with associated value val.
1070
>>> t = _TestClass(123)
1078
"""square() -> square TestClass's associated value
1080
>>> _TestClass(13).square().get()
1084
self.val = self.val ** 2
1088
"""get() -> return TestClass's associated value.
1090
>>> x = _TestClass(-42)
1097
__test__ = {"_TestClass": _TestClass,
1099
Example of a string object, searched as-is.
1108
return doctest.testmod(doctest)
1110
if __name__ == "__main__":