blob: 1b06990e0b591f267482411cf6cdad92b250d768 [file] [log] [blame]
Tim Peters8a7d2d52001-01-16 07:10:57 +00001# Module doctest version 0.9.6
2# Released to the public domain 16-Jan-2001,
3# by Tim Peters (tim.one@home.com).
4
5# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
6
7"""Module doctest -- a framework for running examples in docstrings.
8
9NORMAL USAGE
10
11In normal use, end each module M with:
12
13def _test():
14 import doctest, M # replace M with your module's name
15 return doctest.testmod(M) # ditto
16
17if __name__ == "__main__":
18 _test()
19
20Then running the module as a script will cause the examples in the
21docstrings to get executed and verified:
22
23python M.py
24
25This won't display anything unless an example fails, in which case the
26failing 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
28line of output is "Test failed.".
29
30Run it with the -v switch instead:
31
32python M.py -v
33
34and a detailed report of all examples tried is printed to stdout, along
35with assorted summaries at the end.
36
37You can force verbose mode by passing "verbose=1" to testmod, or prohibit
38it by passing "verbose=0". In either of those cases, sys.argv is not
39examined by testmod.
40
41In any case, testmod returns a 2-tuple of ints (f, t), where f is the
42number of docstring examples that failed and t is the total number of
43docstring examples attempted.
44
45
46WHICH DOCSTRINGS ARE EXAMINED?
47
48+ M.__doc__.
49
50+ f.__doc__ for all functions f in M.__dict__.values(), except those
51 with private names.
52
53+ C.__doc__ for all classes C in M.__dict__.values(), except those with
54 private names.
55
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
63
64Any classes found are recursively searched similarly, to test docstrings in
65their contained methods and nested classes. Private names reached from M's
66globals are skipped, but all names reached from M.__test__ are searched.
67
68By default, a name is considered to be private if it begins with an
69underscore (like "_my_func") but doesn't both begin and end with (at least)
70two underscores (like "__init__"). You can change the default by passing
71your own "isprivate" function to testmod.
72
73If you want to test docstrings in objects with private names too, stuff
74them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
75own isprivate function to Tester's constructor, or call the rundoc method
76of a Tester instance).
77
78Warning: imports can cause trouble; e.g., if you do
79
80from XYZ import XYZclass
81
82then XYZclass is a name in M.__dict__ too, and doctest has no way to know
83that XYZclass wasn't *defined* in M. So it may try to execute the examples
84in XYZclass's docstring, and those in turn may require a different set of
85globals to work correctly. I prefer to do "import *"- friendly imports,
86a la
87
88import XYY
89_XYZclass = XYZ.XYZclass
90del XYZ
91
92or (Python 2.0)
93
94from XYZ import XYZclass as _XYZclass
95
96and then the leading underscore stops testmod from going nuts. You may
97prefer the method in the next section.
98
99
100WHAT'S THE EXECUTION CONTEXT?
101
102By default, each time testmod finds a docstring to test, it uses a *copy*
103of M's globals (so that running tests on a module doesn't change the
104module's real globals, and so that one test in M can't leave behind crumbs
105that accidentally allow another test to work). This means examples can
106freely use any names defined at top-level in M. It also means that sloppy
107imports (see above) can cause examples in external docstrings to use
108globals inappropriate for them.
109
110You 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
112M.__dict__ merged with the globals from other imported modules.
113
114
115WHAT IF I WANT TO TEST A WHOLE PACKAGE?
116
117Piece o' cake, provided the modules do their testing from docstrings.
118Here's the test.py I use for the world's most elaborate Rational/
119floating-base-conversion pkg (which I'll distribute some day):
120
121from Rational import Cvt
122from Rational import Format
123from Rational import machprec
124from Rational import Rat
125from Rational import Round
126from Rational import utils
127
128modules = (Cvt,
129 Format,
130 machprec,
131 Rat,
132 Round,
133 utils)
134
135def _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()
142
143if __name__ == "__main__":
144 _test()
145
146IOW, it just runs testmod on all the pkg modules. testmod remembers the
147names and outcomes (# of failures, # of tries) for each item it's seen, and
148passing "report=0" prevents it from printing a summary in verbose mode.
149Instead, the summary is delayed until all modules have been tested, and
150then "doctest.master.summarize()" forces the summary at the end.
151
152So this is very nice in practice: each module can be tested individually
153with almost no work beyond writing up docstring examples, and collections
154of modules can be tested too as a unit with no more work than the above.
155
156
157WHAT ABOUT EXCEPTIONS?
158
159No problem, as long as the only output generated by the example is the
160traceback itself. For example:
161
162 >>> 1/0
163 Traceback (innermost last):
164 File "<stdin>", line 1, in ?
165 ZeroDivisionError: integer division or modulo by zero
166 >>>
167
168Note that only the exception type and value are compared (specifically,
169only the last line in the traceback).
170
171
172ADVANCED USAGE
173
174doctest.testmod() captures the testing policy I find most useful most
175often. You may want other policies.
176
177testmod() actually creates a local instance of class doctest.Tester, runs
178appropriate methods of that class, and merges the results into global
179Tester instance doctest.master.
180
181You can create your own instances of doctest.Tester, and so build your own
182policies, or even run methods of doctest.master directly. See
183doctest.Tester.__doc__ for details.
184
185
186SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
187
188Oh ya. It's easy! In most cases a copy-and-paste of an interactive
189console session works fine -- just make sure the leading whitespace is
190rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
191right, but doctest is not in the business of guessing what you think a tab
192means).
193
194 >>> # comments are ignored
195 >>> x = 12
196 >>> x
197 12
198 >>> if x == 13:
199 ... print "yes"
200 ... else:
201 ... print "no"
202 ... print "NO"
203 ... print "NO!!!"
204 ...
205 no
206 NO
207 NO!!!
208 >>>
209
210Any expected output must immediately follow the final ">>>" or "..." line
211containing the code, and the expected output (if any) extends to the next
212">>>" or all-whitespace line. That's it.
213
214Bummers:
215
216+ Expected output cannot contain an all-whitespace line, since such a line
217 is taken to signal the end of expected output.
218
219+ Output to stdout is captured, but not output to stderr (exception
220 tracebacks are captured via a different means).
221
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:
226
227>>> if "yes" == \\
228... "y" + \\
229... "es": # in the source code you'll see the doubled backslashes
230... print 'yes'
231yes
232
233The starting column doesn't matter:
234
235>>> assert "Easy!"
236 >>> import math
237 >>> math.floor(1.9)
238 1.0
239
240and as many leading whitespace characters are stripped from the expected
241output as appeared in the initial ">>>" line that triggered it.
242
243If you execute this very file, the examples above will be found and
244executed, leading to this output in verbose mode:
245
246Running doctest.__doc__
247Trying: 1/0
248Expecting:
249Traceback (innermost last):
250 File "<stdin>", line 1, in ?
251ZeroDivisionError: integer division or modulo by zero
252ok
253Trying: x = 12
254Expecting: nothing
255ok
256Trying: x
257Expecting: 12
258ok
259Trying:
260if x == 13:
261 print "yes"
262else:
263 print "no"
264 print "NO"
265 print "NO!!!"
266Expecting:
267no
268NO
269NO!!!
270ok
271... and a bunch more like that, with this summary at the end:
272
2735 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
27912 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
29253 tests in 17 items.
29353 passed and 0 failed.
294Test passed.
295"""
296
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
349__version__ = 0, 9, 6
350
351import types
352_FunctionType = types.FunctionType
353_ClassType = types.ClassType
354_ModuleType = types.ModuleType
355_StringType = types.StringType
356del types
357
358import string
359_string_find = string.find
360_string_join = string.join
361_string_split = string.split
362_string_rindex = string.rindex
363del string
364
365import re
366PS1 = ">>>"
367PS2 = "..."
368_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
369_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
370_isEmpty = re.compile(r"\s*$").match
371_isComment = re.compile(r"\s*#").match
372del re
373
374# Extract interactive examples from a string. Return a list of triples,
375# (source, outcome, lineno). "source" is the source code, and ends
376# with a newline iff the source spans more than one line. "outcome" is
377# the expected output if any, else an empty string. When not empty,
378# outcome always ends with a newline. "lineno" is the line number,
379# 0-based wrt the start of the string, of the first source line.
380
381def _extract_examples(s):
382 isPS1, isPS2 = _isPS1, _isPS2
383 isEmpty, isComment = _isEmpty, _isComment
384 examples = []
385 lines = _string_split(s, "\n")
386 i, n = 0, len(lines)
387 while i < n:
388 line = lines[i]
389 i = i + 1
390 m = isPS1(line)
391 if m is None:
392 continue
393 j = m.end(0) # beyond the prompt
394 if isEmpty(line, j) or isComment(line, j):
395 # a bare prompt or comment -- not interesting
396 continue
397 lineno = i - 1
398 if line[j] != " ":
399 raise ValueError("line " + `lineno` + " of docstring lacks "
400 "blank after " + PS1 + ": " + line)
401 j = j + 1
402 blanks = m.group(1)
403 nblanks = len(blanks)
404 # suck up this and following PS2 lines
405 source = []
406 while 1:
407 source.append(line[j:])
408 line = lines[i]
409 m = isPS2(line)
410 if m:
411 if m.group(1) != blanks:
412 raise ValueError("inconsistent leading whitespace "
413 "in line " + `i` + " of docstring: " + line)
414 i = i + 1
415 else:
416 break
417 if len(source) == 1:
418 source = source[0]
419 else:
420 # get rid of useless null line from trailing empty "..."
421 if source[-1] == "":
422 del source[-1]
423 source = _string_join(source, "\n") + "\n"
424 # suck up response
425 if isPS1(line) or isEmpty(line):
426 expect = ""
427 else:
428 expect = []
429 while 1:
430 if line[:nblanks] != blanks:
431 raise ValueError("inconsistent leading whitespace "
432 "in line " + `i` + " of docstring: " + line)
433 expect.append(line[nblanks:])
434 i = i + 1
435 line = lines[i]
436 if isPS1(line) or isEmpty(line):
437 break
438 expect = _string_join(expect, "\n") + "\n"
439 examples.append( (source, expect, lineno) )
440 return examples
441
442# Capture stdout when running examples.
443
444class _SpoofOut:
445 def __init__(self):
446 self.clear()
447 def write(self, s):
448 self.buf.append(s)
449 def get(self):
450 return _string_join(self.buf, "")
451 def clear(self):
452 self.buf = []
453 def flush(self):
454 # JPython calls flush
455 pass
456
457# Display some tag-and-msg pairs nicely, keeping the tag and its msg
458# on the same line when that makes sense.
459
460def _tag_out(printer, *tag_msg_pairs):
461 for tag, msg in tag_msg_pairs:
462 printer(tag + ":")
463 msg_has_nl = msg[-1:] == "\n"
464 msg_has_two_nl = msg_has_nl and \
465 _string_find(msg, "\n") < len(msg) - 1
466 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
467 printer(" ")
468 else:
469 printer("\n")
470 printer(msg)
471 if not msg_has_nl:
472 printer("\n")
473
474# Run list of examples, in context globs. "out" can be used to display
475# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
476# that captures the examples' std output. Return (#failures, #tries).
477
478def _run_examples_inner(out, fakeout, examples, globs, verbose, name):
479 import sys, traceback
480 OK, BOOM, FAIL = range(3)
481 NADA = "nothing"
482 stderr = _SpoofOut()
483 failures = 0
484 for source, want, lineno in examples:
485 if verbose:
486 _tag_out(out, ("Trying", source),
487 ("Expecting", want or NADA))
488 fakeout.clear()
489 try:
490 exec compile(source, "<string>", "single") in globs
491 got = fakeout.get()
492 state = OK
493 except:
494 # See whether the exception was expected.
495 if _string_find(want, "Traceback (innermost last):\n") == 0:
496 # Only compare exception type and value - the rest of
497 # the traceback isn't necessary.
498 want = _string_split(want, '\n')[-2] + '\n'
499 exc_type, exc_val, exc_tb = sys.exc_info()
500 got = traceback.format_exception_only(exc_type, exc_val)[0]
501 state = OK
502 else:
503 # unexpected exception
504 stderr.clear()
505 traceback.print_exc(file=stderr)
506 state = BOOM
507
508 if state == OK:
509 if got == want:
510 if verbose:
511 out("ok\n")
512 continue
513 state = FAIL
514
515 assert state in (FAIL, BOOM)
516 failures = failures + 1
517 out("*" * 65 + "\n")
518 _tag_out(out, ("Failure in example", source))
519 out("from line #" + `lineno` + " of " + name + "\n")
520 if state == FAIL:
521 _tag_out(out, ("Expected", want or NADA), ("Got", got))
522 else:
523 assert state == BOOM
524 _tag_out(out, ("Exception raised", stderr.get()))
525
526 return failures, len(examples)
527
528# Run list of examples, in context globs. Return (#failures, #tries).
529
530def _run_examples(examples, globs, verbose, name):
531 import sys
532 saveout = sys.stdout
533 try:
534 sys.stdout = fakeout = _SpoofOut()
535 x = _run_examples_inner(saveout.write, fakeout, examples,
536 globs, verbose, name)
537 finally:
538 sys.stdout = saveout
539 return x
540
541def run_docstring_examples(f, globs, verbose=0, name="NoName"):
542 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
543
544 Use dict globs as the globals for execution.
545 Return (#failures, #tries).
546
547 If optional arg verbose is true, print stuff even if there are no
548 failures.
549 Use string name in failure msgs.
550 """
551
552 try:
553 doc = f.__doc__
554 if not doc:
555 # docstring empty or None
556 return 0, 0
557 # just in case CT invents a doc object that has to be forced
558 # to look like a string <0.9 wink>
559 doc = str(doc)
560 except:
561 return 0, 0
562
563 e = _extract_examples(doc)
564 if not e:
565 return 0, 0
566 return _run_examples(e, globs, verbose, name)
567
568def is_private(prefix, base):
569 """prefix, base -> true iff name prefix + "." + base is "private".
570
571 Prefix may be an empty string, and base does not contain a period.
572 Prefix is ignored (although functions you write conforming to this
573 protocol may make use of it).
574 Return true iff base begins with an (at least one) underscore, but
575 does not both begin and end with (at least) two underscores.
576
577 >>> is_private("a.b", "my_func")
578 0
579 >>> is_private("____", "_my_func")
580 1
581 >>> is_private("someclass", "__init__")
582 0
583 >>> is_private("sometypo", "__init_")
584 1
585 >>> is_private("x.y.z", "_")
586 1
587 >>> is_private("_x.y.z", "__")
588 0
589 >>> is_private("", "") # senseless but consistent
590 0
591 """
592
593 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
594
595class Tester:
596 """Class Tester -- runs docstring examples and accumulates stats.
597
598In normal use, function doctest.testmod() hides all this from you,
599so use that if you can. Create your own instances of Tester to do
600fancier things.
601
602Methods:
603 runstring(s, name)
604 Search string s for examples to run; use name for logging.
605 Return (#failures, #tries).
606
607 rundoc(object, name=None)
608 Search object.__doc__ for examples to run; use name (or
609 object.__name__) for logging. Return (#failures, #tries).
610
611 rundict(d, name)
612 Search for examples in docstrings in all of d.values(); use name
613 for logging. Return (#failures, #tries).
614
615 run__test__(d, name)
616 Treat dict d like module.__test__. Return (#failures, #tries).
617
618 summarize(verbose=None)
619 Display summary of testing results, to stdout. Return
620 (#failures, #tries).
621
622 merge(other)
623 Merge in the test results from Tester instance "other".
624
625>>> from doctest import Tester
626>>> t = Tester(globs={'x': 42}, verbose=0)
627>>> t.runstring(r'''
628... >>> x = x * 2
629... >>> print x
630... 42
631... ''', 'XYZ')
632*****************************************************************
633Failure in example: print x
634from line #2 of XYZ
635Expected: 42
636Got: 84
637(1, 2)
638>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
639(0, 2)
640>>> t.summarize()
6411 items had failures:
642 1 of 2 in XYZ
643***Test Failed*** 1 failures.
644(1, 4)
645>>> t.summarize(verbose=1)
6461 items passed all tests:
647 2 tests in example2
6481 items had failures:
649 1 of 2 in XYZ
6504 tests in 2 items.
6513 passed and 1 failed.
652***Test Failed*** 1 failures.
653(1, 4)
654>>>
655"""
656
657 def __init__(self, mod=None, globs=None, verbose=None,
658 isprivate=None):
659 """mod=None, globs=None, verbose=None, isprivate=None
660
661See doctest.__doc__ for an overview.
662
663Optional keyword arg "mod" is a module, whose globals are used for
664executing examples. If not specified, globs must be specified.
665
666Optional keyword arg "globs" gives a dict to be used as the globals
667when executing examples; if not specified, use the globals from
668module mod.
669
670In either case, a copy of the dict is used for each docstring
671examined.
672
673Optional keyword arg "verbose" prints lots of stuff if true, only
674failures if false; by default, it's true iff "-v" is in sys.argv.
675
676Optional keyword arg "isprivate" specifies a function used to determine
677whether a name is private. The default function is doctest.is_private;
678see its docs for details.
679"""
680
681 if mod is None and globs is None:
682 raise TypeError("Tester.__init__: must specify mod or globs")
683 if mod is not None and type(mod) is not _ModuleType:
684 raise TypeError("Tester.__init__: mod must be a module; " +
685 `mod`)
686 if globs is None:
687 globs = mod.__dict__
688 self.globs = globs
689
690 if verbose is None:
691 import sys
692 verbose = "-v" in sys.argv
693 self.verbose = verbose
694
695 if isprivate is None:
696 isprivate = is_private
697 self.isprivate = isprivate
698
699 self.name2ft = {} # map name to (#failures, #trials) pair
700
701 def runstring(self, s, name):
702 """
703 s, name -> search string s for examples to run, logging as name.
704
705 Use string name as the key for logging the outcome.
706 Return (#failures, #examples).
707
708 >>> t = Tester(globs={}, verbose=1)
709 >>> test = r'''
710 ... # just an example
711 ... >>> x = 1 + 2
712 ... >>> x
713 ... 3
714 ... '''
715 >>> t.runstring(test, "Example")
716 Running string Example
717 Trying: x = 1 + 2
718 Expecting: nothing
719 ok
720 Trying: x
721 Expecting: 3
722 ok
723 0 of 2 examples failed in string Example
724 (0, 2)
725 """
726
727 if self.verbose:
728 print "Running string", name
729 f = t = 0
730 e = _extract_examples(s)
731 if e:
732 f, t = _run_examples(e, self.globs.copy(), self.verbose, name)
733 if self.verbose:
734 print f, "of", t, "examples failed in string", name
735 self.__record_outcome(name, f, t)
736 return f, t
737
738 def rundoc(self, object, name=None):
739 """
740 object, name=None -> search object.__doc__ for examples to run.
741
742 Use optional string name as the key for logging the outcome;
743 by default use object.__name__.
744 Return (#failures, #examples).
745 If object is a class object, search recursively for method
746 docstrings too.
747 object.__doc__ is examined regardless of name, but if object is
748 a class, whether private names reached from object are searched
749 depends on the constructor's "isprivate" argument.
750
751 >>> t = Tester(globs={}, verbose=0)
752 >>> def _f():
753 ... '''Trivial docstring example.
754 ... >>> assert 2 == 2
755 ... '''
756 ... return 32
757 ...
758 >>> t.rundoc(_f) # expect 0 failures in 1 example
759 (0, 1)
760 """
761
762 if name is None:
763 try:
764 name = object.__name__
765 except AttributeError:
766 raise ValueError("Tester.rundoc: name must be given "
767 "when object.__name__ doesn't exist; " + `object`)
768 if self.verbose:
769 print "Running", name + ".__doc__"
770 f, t = run_docstring_examples(object, self.globs.copy(),
771 self.verbose, name)
772 if self.verbose:
773 print f, "of", t, "examples failed in", name + ".__doc__"
774 self.__record_outcome(name, f, t)
775 if type(object) is _ClassType:
776 f2, t2 = self.rundict(object.__dict__, name)
777 f = f + f2
778 t = t + t2
779 return f, t
780
781 def rundict(self, d, name):
782 """
783 d. name -> search for docstring examples in all of d.values().
784
785 For k, v in d.items() such that v is a function or class,
786 do self.rundoc(v, name + "." + k). Whether this includes
787 objects with private names depends on the constructor's
788 "isprivate" argument.
789 Return aggregate (#failures, #examples).
790
791 >>> def _f():
792 ... '''>>> assert 1 == 1
793 ... '''
794 >>> def g():
795 ... '''>>> assert 2 != 1
796 ... '''
797 >>> d = {"_f": _f, "g": g}
798 >>> t = Tester(globs={}, verbose=0)
799 >>> t.rundict(d, "rundict_test") # _f is skipped
800 (0, 1)
801 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
802 >>> t.rundict(d, "rundict_test_pvt") # both are searched
803 (0, 2)
804 """
805
806 if not hasattr(d, "items"):
807 raise TypeError("Tester.rundict: d must support .items(); " +
808 `d`)
809 f = t = 0
810 for thisname, value in d.items():
811 if type(value) in (_FunctionType, _ClassType):
812 f2, t2 = self.__runone(value, name + "." + thisname)
813 f = f + f2
814 t = t + t2
815 return f, t
816
817 def run__test__(self, d, name):
818 """d, name -> Treat dict d like module.__test__.
819
820 Return (#failures, #tries).
821 See testmod.__doc__ for details.
822 """
823
824 failures = tries = 0
825 prefix = name + "."
826 savepvt = self.isprivate
827 try:
828 self.isprivate = lambda *args: 0
829 for k, v in d.items():
830 thisname = prefix + k
831 if type(v) is _StringType:
832 f, t = self.runstring(v, thisname)
833 elif type(v) in (_FunctionType, _ClassType):
834 f, t = self.rundoc(v, thisname)
835 else:
836 raise TypeError("Tester.run__test__: values in "
837 "dict must be strings, functions "
838 "or classes; " + `v`)
839 failures = failures + f
840 tries = tries + t
841 finally:
842 self.isprivate = savepvt
843 return failures, tries
844
845 def summarize(self, verbose=None):
846 """
847 verbose=None -> summarize results, return (#failures, #tests).
848
849 Print summary of test results to stdout.
850 Optional arg 'verbose' controls how wordy this is. By
851 default, use the verbose setting established by the
852 constructor.
853 """
854
855 if verbose is None:
856 verbose = self.verbose
857 notests = []
858 passed = []
859 failed = []
860 totalt = totalf = 0
861 for x in self.name2ft.items():
862 name, (f, t) = x
863 assert f <= t
864 totalt = totalt + t
865 totalf = totalf + f
866 if t == 0:
867 notests.append(name)
868 elif f == 0:
869 passed.append( (name, t) )
870 else:
871 failed.append(x)
872 if verbose:
873 if notests:
874 print len(notests), "items had no tests:"
875 notests.sort()
876 for thing in notests:
877 print " ", thing
878 if passed:
879 print len(passed), "items passed all tests:"
880 passed.sort()
881 for thing, count in passed:
882 print " %3d tests in %s" % (count, thing)
883 if failed:
884 print len(failed), "items had failures:"
885 failed.sort()
886 for thing, (f, t) in failed:
887 print " %3d of %3d in %s" % (f, t, thing)
888 if verbose:
889 print totalt, "tests in", len(self.name2ft), "items."
890 print totalt - totalf, "passed and", totalf, "failed."
891 if totalf:
892 print "***Test Failed***", totalf, "failures."
893 elif verbose:
894 print "Test passed."
895 return totalf, totalt
896
897 def merge(self, other):
898 """
899 other -> merge in test results from the other Tester instance.
900
901 If self and other both have a test result for something
902 with the same name, the (#failures, #tests) results are
903 summed, and a warning is printed to stdout.
904
905 >>> from doctest import Tester
906 >>> t1 = Tester(globs={}, verbose=0)
907 >>> t1.runstring('''
908 ... >>> x = 12
909 ... >>> print x
910 ... 12
911 ... ''', "t1example")
912 (0, 2)
913 >>>
914 >>> t2 = Tester(globs={}, verbose=0)
915 >>> t2.runstring('''
916 ... >>> x = 13
917 ... >>> print x
918 ... 13
919 ... ''', "t2example")
920 (0, 2)
921 >>> common = ">>> assert 1 + 2 == 3\\n"
922 >>> t1.runstring(common, "common")
923 (0, 1)
924 >>> t2.runstring(common, "common")
925 (0, 1)
926 >>> t1.merge(t2)
927 *** Tester.merge: 'common' in both testers; summing outcomes.
928 >>> t1.summarize(1)
929 3 items passed all tests:
930 2 tests in common
931 2 tests in t1example
932 2 tests in t2example
933 6 tests in 3 items.
934 6 passed and 0 failed.
935 Test passed.
936 (0, 6)
937 >>>
938 """
939
940 d = self.name2ft
941 for name, (f, t) in other.name2ft.items():
942 if d.has_key(name):
943 print "*** Tester.merge: '" + name + "' in both" \
944 " testers; summing outcomes."
945 f2, t2 = d[name]
946 f = f + f2
947 t = t + t2
948 d[name] = f, t
949
950 def __record_outcome(self, name, f, t):
951 if self.name2ft.has_key(name):
952 print "*** Warning: '" + name + "' was tested before;", \
953 "summing outcomes."
954 f2, t2 = self.name2ft[name]
955 f = f + f2
956 t = t + t2
957 self.name2ft[name] = f, t
958
959 def __runone(self, target, name):
960 if "." in name:
961 i = _string_rindex(name, ".")
962 prefix, base = name[:i], name[i+1:]
963 else:
964 prefix, base = "", base
965 if self.isprivate(prefix, base):
966 return 0, 0
967 return self.rundoc(target, name)
968
969master = None
970
971def testmod(m, name=None, globs=None, verbose=None, isprivate=None,
972 report=1):
973 """m, name=None, globs=None, verbose=None, isprivate=None, report=1
974
975 Test examples in docstrings in functions and classes reachable from
976 module m, starting with m.__doc__. Private names are skipped.
977
978 Also test examples reachable from dict m.__test__ if it exists and is
979 not None. m.__dict__ maps names to functions, classes and strings;
980 function and class docstrings are tested even if the name is private;
981 strings are tested directly, as if they were docstrings.
982
983 Return (#failures, #tests).
984
985 See doctest.__doc__ for an overview.
986
987 Optional keyword arg "name" gives the name of the module; by default
988 use m.__name__.
989
990 Optional keyword arg "globs" gives a dict to be used as the globals
991 when executing examples; by default, use m.__dict__. A copy of this
992 dict is actually used for each docstring, so that each docstring's
993 examples start with a clean slate.
994
995 Optional keyword arg "verbose" prints lots of stuff if true, prints
996 only failures if false; by default, it's true iff "-v" is in sys.argv.
997
998 Optional keyword arg "isprivate" specifies a function used to
999 determine whether a name is private. The default function is
1000 doctest.is_private; see its docs for details.
1001
1002 Optional keyword arg "report" prints a summary at the end when true,
1003 else prints nothing at the end. In verbose mode, the summary is
1004 detailed, else very brief (in fact, empty if all tests passed).
1005
1006 Advanced tomfoolery: testmod runs methods of a local instance of
1007 class doctest.Tester, then merges the results into (or creates)
1008 global Tester instance doctest.master. Methods of doctest.master
1009 can be called directly too, if you want to do something unusual.
1010 Passing report=0 to testmod is especially useful then, to delay
1011 displaying a summary. Invoke doctest.master.summarize(verbose)
1012 when you're done fiddling.
1013 """
1014
1015 global master
1016
1017 if type(m) is not _ModuleType:
1018 raise TypeError("testmod: module required; " + `m`)
1019 if name is None:
1020 name = m.__name__
1021 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate)
1022 failures, tries = tester.rundoc(m, name)
1023 f, t = tester.rundict(m.__dict__, name)
1024 failures = failures + f
1025 tries = tries + t
1026 if hasattr(m, "__test__"):
1027 testdict = m.__test__
1028 if testdict:
1029 if not hasattr(testdict, "items"):
1030 raise TypeError("testmod: module.__test__ must support "
1031 ".items(); " + `testdict`)
1032 f, t = tester.run__test__(testdict, name + ".__test__")
1033 failures = failures + f
1034 tries = tries + t
1035 if report:
1036 tester.summarize()
1037 if master is None:
1038 master = tester
1039 else:
1040 master.merge(tester)
1041 return failures, tries
1042
1043class _TestClass:
1044 """
1045 A pointless class, for sanity-checking of docstring testing.
1046
1047 Methods:
1048 square()
1049 get()
1050
1051 >>> _TestClass(13).get() + _TestClass(-12).get()
1052 1
1053 >>> hex(_TestClass(13).square().get())
1054 '0xa9'
1055 """
1056
1057 def __init__(self, val):
1058 """val -> _TestClass object with associated value val.
1059
1060 >>> t = _TestClass(123)
1061 >>> print t.get()
1062 123
1063 """
1064
1065 self.val = val
1066
1067 def square(self):
1068 """square() -> square TestClass's associated value
1069
1070 >>> _TestClass(13).square().get()
1071 169
1072 """
1073
1074 self.val = self.val ** 2
1075 return self
1076
1077 def get(self):
1078 """get() -> return TestClass's associated value.
1079
1080 >>> x = _TestClass(-42)
1081 >>> print x.get()
1082 -42
1083 """
1084
1085 return self.val
1086
1087__test__ = {"_TestClass": _TestClass,
1088 "string": r"""
1089 Example of a string object, searched as-is.
1090 >>> x = 1; y = 2
1091 >>> x + y, x * y
1092 (3, 2)
1093 """
1094 }
1095
1096def _test():
1097 import doctest
1098 return doctest.testmod(doctest)
1099
1100if __name__ == "__main__":
1101 _test()