blob: 7b4e3fe1aac548991592ac04e8b714e8498e086f [file] [log] [blame]
Eric S. Raymond630e69c2001-02-09 08:33:43 +00001# Module doctest version 0.9.7
Tim Peters8a7d2d52001-01-16 07:10:57 +00002# 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>.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000348# 0,9,7 9-Feb-2001
349# string method conversion
Tim Peters8a7d2d52001-01-16 07:10:57 +0000350
351__version__ = 0, 9, 6
352
353import types
354_FunctionType = types.FunctionType
355_ClassType = types.ClassType
356_ModuleType = types.ModuleType
357_StringType = types.StringType
358del types
359
Tim Peters8a7d2d52001-01-16 07:10:57 +0000360import re
361PS1 = ">>>"
362PS2 = "..."
363_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
364_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
365_isEmpty = re.compile(r"\s*$").match
366_isComment = re.compile(r"\s*#").match
367del re
368
Skip Montanaroeccd02a2001-01-20 23:34:12 +0000369__all__ = []
370
Tim Peters8a7d2d52001-01-16 07:10:57 +0000371# Extract interactive examples from a string. Return a list of triples,
372# (source, outcome, lineno). "source" is the source code, and ends
373# with a newline iff the source spans more than one line. "outcome" is
374# the expected output if any, else an empty string. When not empty,
375# outcome always ends with a newline. "lineno" is the line number,
376# 0-based wrt the start of the string, of the first source line.
377
378def _extract_examples(s):
379 isPS1, isPS2 = _isPS1, _isPS2
380 isEmpty, isComment = _isEmpty, _isComment
381 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000382 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000383 i, n = 0, len(lines)
384 while i < n:
385 line = lines[i]
386 i = i + 1
387 m = isPS1(line)
388 if m is None:
389 continue
390 j = m.end(0) # beyond the prompt
391 if isEmpty(line, j) or isComment(line, j):
392 # a bare prompt or comment -- not interesting
393 continue
394 lineno = i - 1
395 if line[j] != " ":
396 raise ValueError("line " + `lineno` + " of docstring lacks "
397 "blank after " + PS1 + ": " + line)
398 j = j + 1
399 blanks = m.group(1)
400 nblanks = len(blanks)
401 # suck up this and following PS2 lines
402 source = []
403 while 1:
404 source.append(line[j:])
405 line = lines[i]
406 m = isPS2(line)
407 if m:
408 if m.group(1) != blanks:
409 raise ValueError("inconsistent leading whitespace "
410 "in line " + `i` + " of docstring: " + line)
411 i = i + 1
412 else:
413 break
414 if len(source) == 1:
415 source = source[0]
416 else:
417 # get rid of useless null line from trailing empty "..."
418 if source[-1] == "":
419 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000420 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000421 # suck up response
422 if isPS1(line) or isEmpty(line):
423 expect = ""
424 else:
425 expect = []
426 while 1:
427 if line[:nblanks] != blanks:
428 raise ValueError("inconsistent leading whitespace "
429 "in line " + `i` + " of docstring: " + line)
430 expect.append(line[nblanks:])
431 i = i + 1
432 line = lines[i]
433 if isPS1(line) or isEmpty(line):
434 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000435 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000436 examples.append( (source, expect, lineno) )
437 return examples
438
439# Capture stdout when running examples.
440
441class _SpoofOut:
442 def __init__(self):
443 self.clear()
444 def write(self, s):
445 self.buf.append(s)
446 def get(self):
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000447 return "".join(self.buf)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000448 def clear(self):
449 self.buf = []
450 def flush(self):
451 # JPython calls flush
452 pass
453
454# Display some tag-and-msg pairs nicely, keeping the tag and its msg
455# on the same line when that makes sense.
456
457def _tag_out(printer, *tag_msg_pairs):
458 for tag, msg in tag_msg_pairs:
459 printer(tag + ":")
460 msg_has_nl = msg[-1:] == "\n"
461 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000462 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000463 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
464 printer(" ")
465 else:
466 printer("\n")
467 printer(msg)
468 if not msg_has_nl:
469 printer("\n")
470
471# Run list of examples, in context globs. "out" can be used to display
472# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
473# that captures the examples' std output. Return (#failures, #tries).
474
475def _run_examples_inner(out, fakeout, examples, globs, verbose, name):
476 import sys, traceback
477 OK, BOOM, FAIL = range(3)
478 NADA = "nothing"
479 stderr = _SpoofOut()
480 failures = 0
481 for source, want, lineno in examples:
482 if verbose:
483 _tag_out(out, ("Trying", source),
484 ("Expecting", want or NADA))
485 fakeout.clear()
486 try:
487 exec compile(source, "<string>", "single") in globs
488 got = fakeout.get()
489 state = OK
490 except:
491 # See whether the exception was expected.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000492 if want.find("Traceback (innermost last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000493 # Only compare exception type and value - the rest of
494 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000495 want = want.split('\n')[-2] + '\n'
Tim Peters8a7d2d52001-01-16 07:10:57 +0000496 exc_type, exc_val, exc_tb = sys.exc_info()
497 got = traceback.format_exception_only(exc_type, exc_val)[0]
498 state = OK
499 else:
500 # unexpected exception
501 stderr.clear()
502 traceback.print_exc(file=stderr)
503 state = BOOM
504
505 if state == OK:
506 if got == want:
507 if verbose:
508 out("ok\n")
509 continue
510 state = FAIL
511
512 assert state in (FAIL, BOOM)
513 failures = failures + 1
514 out("*" * 65 + "\n")
515 _tag_out(out, ("Failure in example", source))
516 out("from line #" + `lineno` + " of " + name + "\n")
517 if state == FAIL:
518 _tag_out(out, ("Expected", want or NADA), ("Got", got))
519 else:
520 assert state == BOOM
521 _tag_out(out, ("Exception raised", stderr.get()))
522
523 return failures, len(examples)
524
525# Run list of examples, in context globs. Return (#failures, #tries).
526
527def _run_examples(examples, globs, verbose, name):
528 import sys
529 saveout = sys.stdout
530 try:
531 sys.stdout = fakeout = _SpoofOut()
532 x = _run_examples_inner(saveout.write, fakeout, examples,
533 globs, verbose, name)
534 finally:
535 sys.stdout = saveout
536 return x
537
538def run_docstring_examples(f, globs, verbose=0, name="NoName"):
539 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
540
541 Use dict globs as the globals for execution.
542 Return (#failures, #tries).
543
544 If optional arg verbose is true, print stuff even if there are no
545 failures.
546 Use string name in failure msgs.
547 """
548
549 try:
550 doc = f.__doc__
551 if not doc:
552 # docstring empty or None
553 return 0, 0
554 # just in case CT invents a doc object that has to be forced
555 # to look like a string <0.9 wink>
556 doc = str(doc)
557 except:
558 return 0, 0
559
560 e = _extract_examples(doc)
561 if not e:
562 return 0, 0
563 return _run_examples(e, globs, verbose, name)
564
565def is_private(prefix, base):
566 """prefix, base -> true iff name prefix + "." + base is "private".
567
568 Prefix may be an empty string, and base does not contain a period.
569 Prefix is ignored (although functions you write conforming to this
570 protocol may make use of it).
571 Return true iff base begins with an (at least one) underscore, but
572 does not both begin and end with (at least) two underscores.
573
574 >>> is_private("a.b", "my_func")
575 0
576 >>> is_private("____", "_my_func")
577 1
578 >>> is_private("someclass", "__init__")
579 0
580 >>> is_private("sometypo", "__init_")
581 1
582 >>> is_private("x.y.z", "_")
583 1
584 >>> is_private("_x.y.z", "__")
585 0
586 >>> is_private("", "") # senseless but consistent
587 0
588 """
589
590 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
591
592class Tester:
593 """Class Tester -- runs docstring examples and accumulates stats.
594
595In normal use, function doctest.testmod() hides all this from you,
596so use that if you can. Create your own instances of Tester to do
597fancier things.
598
599Methods:
600 runstring(s, name)
601 Search string s for examples to run; use name for logging.
602 Return (#failures, #tries).
603
604 rundoc(object, name=None)
605 Search object.__doc__ for examples to run; use name (or
606 object.__name__) for logging. Return (#failures, #tries).
607
608 rundict(d, name)
609 Search for examples in docstrings in all of d.values(); use name
610 for logging. Return (#failures, #tries).
611
612 run__test__(d, name)
613 Treat dict d like module.__test__. Return (#failures, #tries).
614
615 summarize(verbose=None)
616 Display summary of testing results, to stdout. Return
617 (#failures, #tries).
618
619 merge(other)
620 Merge in the test results from Tester instance "other".
621
622>>> from doctest import Tester
623>>> t = Tester(globs={'x': 42}, verbose=0)
624>>> t.runstring(r'''
625... >>> x = x * 2
626... >>> print x
627... 42
628... ''', 'XYZ')
629*****************************************************************
630Failure in example: print x
631from line #2 of XYZ
632Expected: 42
633Got: 84
634(1, 2)
635>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
636(0, 2)
637>>> t.summarize()
6381 items had failures:
639 1 of 2 in XYZ
640***Test Failed*** 1 failures.
641(1, 4)
642>>> t.summarize(verbose=1)
6431 items passed all tests:
644 2 tests in example2
6451 items had failures:
646 1 of 2 in XYZ
6474 tests in 2 items.
6483 passed and 1 failed.
649***Test Failed*** 1 failures.
650(1, 4)
651>>>
652"""
653
654 def __init__(self, mod=None, globs=None, verbose=None,
655 isprivate=None):
656 """mod=None, globs=None, verbose=None, isprivate=None
657
658See doctest.__doc__ for an overview.
659
660Optional keyword arg "mod" is a module, whose globals are used for
661executing examples. If not specified, globs must be specified.
662
663Optional keyword arg "globs" gives a dict to be used as the globals
664when executing examples; if not specified, use the globals from
665module mod.
666
667In either case, a copy of the dict is used for each docstring
668examined.
669
670Optional keyword arg "verbose" prints lots of stuff if true, only
671failures if false; by default, it's true iff "-v" is in sys.argv.
672
673Optional keyword arg "isprivate" specifies a function used to determine
674whether a name is private. The default function is doctest.is_private;
675see its docs for details.
676"""
677
678 if mod is None and globs is None:
679 raise TypeError("Tester.__init__: must specify mod or globs")
680 if mod is not None and type(mod) is not _ModuleType:
681 raise TypeError("Tester.__init__: mod must be a module; " +
682 `mod`)
683 if globs is None:
684 globs = mod.__dict__
685 self.globs = globs
686
687 if verbose is None:
688 import sys
689 verbose = "-v" in sys.argv
690 self.verbose = verbose
691
692 if isprivate is None:
693 isprivate = is_private
694 self.isprivate = isprivate
695
696 self.name2ft = {} # map name to (#failures, #trials) pair
697
698 def runstring(self, s, name):
699 """
700 s, name -> search string s for examples to run, logging as name.
701
702 Use string name as the key for logging the outcome.
703 Return (#failures, #examples).
704
705 >>> t = Tester(globs={}, verbose=1)
706 >>> test = r'''
707 ... # just an example
708 ... >>> x = 1 + 2
709 ... >>> x
710 ... 3
711 ... '''
712 >>> t.runstring(test, "Example")
713 Running string Example
714 Trying: x = 1 + 2
715 Expecting: nothing
716 ok
717 Trying: x
718 Expecting: 3
719 ok
720 0 of 2 examples failed in string Example
721 (0, 2)
722 """
723
724 if self.verbose:
725 print "Running string", name
726 f = t = 0
727 e = _extract_examples(s)
728 if e:
729 f, t = _run_examples(e, self.globs.copy(), self.verbose, name)
730 if self.verbose:
731 print f, "of", t, "examples failed in string", name
732 self.__record_outcome(name, f, t)
733 return f, t
734
735 def rundoc(self, object, name=None):
736 """
737 object, name=None -> search object.__doc__ for examples to run.
738
739 Use optional string name as the key for logging the outcome;
740 by default use object.__name__.
741 Return (#failures, #examples).
742 If object is a class object, search recursively for method
743 docstrings too.
744 object.__doc__ is examined regardless of name, but if object is
745 a class, whether private names reached from object are searched
746 depends on the constructor's "isprivate" argument.
747
748 >>> t = Tester(globs={}, verbose=0)
749 >>> def _f():
750 ... '''Trivial docstring example.
751 ... >>> assert 2 == 2
752 ... '''
753 ... return 32
754 ...
755 >>> t.rundoc(_f) # expect 0 failures in 1 example
756 (0, 1)
757 """
758
759 if name is None:
760 try:
761 name = object.__name__
762 except AttributeError:
763 raise ValueError("Tester.rundoc: name must be given "
764 "when object.__name__ doesn't exist; " + `object`)
765 if self.verbose:
766 print "Running", name + ".__doc__"
767 f, t = run_docstring_examples(object, self.globs.copy(),
768 self.verbose, name)
769 if self.verbose:
770 print f, "of", t, "examples failed in", name + ".__doc__"
771 self.__record_outcome(name, f, t)
772 if type(object) is _ClassType:
773 f2, t2 = self.rundict(object.__dict__, name)
774 f = f + f2
775 t = t + t2
776 return f, t
777
778 def rundict(self, d, name):
779 """
780 d. name -> search for docstring examples in all of d.values().
781
782 For k, v in d.items() such that v is a function or class,
783 do self.rundoc(v, name + "." + k). Whether this includes
784 objects with private names depends on the constructor's
785 "isprivate" argument.
786 Return aggregate (#failures, #examples).
787
788 >>> def _f():
789 ... '''>>> assert 1 == 1
790 ... '''
791 >>> def g():
792 ... '''>>> assert 2 != 1
793 ... '''
794 >>> d = {"_f": _f, "g": g}
795 >>> t = Tester(globs={}, verbose=0)
796 >>> t.rundict(d, "rundict_test") # _f is skipped
797 (0, 1)
798 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
799 >>> t.rundict(d, "rundict_test_pvt") # both are searched
800 (0, 2)
801 """
802
803 if not hasattr(d, "items"):
804 raise TypeError("Tester.rundict: d must support .items(); " +
805 `d`)
806 f = t = 0
807 for thisname, value in d.items():
808 if type(value) in (_FunctionType, _ClassType):
809 f2, t2 = self.__runone(value, name + "." + thisname)
810 f = f + f2
811 t = t + t2
812 return f, t
813
814 def run__test__(self, d, name):
815 """d, name -> Treat dict d like module.__test__.
816
817 Return (#failures, #tries).
818 See testmod.__doc__ for details.
819 """
820
821 failures = tries = 0
822 prefix = name + "."
823 savepvt = self.isprivate
824 try:
825 self.isprivate = lambda *args: 0
826 for k, v in d.items():
827 thisname = prefix + k
828 if type(v) is _StringType:
829 f, t = self.runstring(v, thisname)
830 elif type(v) in (_FunctionType, _ClassType):
831 f, t = self.rundoc(v, thisname)
832 else:
833 raise TypeError("Tester.run__test__: values in "
834 "dict must be strings, functions "
835 "or classes; " + `v`)
836 failures = failures + f
837 tries = tries + t
838 finally:
839 self.isprivate = savepvt
840 return failures, tries
841
842 def summarize(self, verbose=None):
843 """
844 verbose=None -> summarize results, return (#failures, #tests).
845
846 Print summary of test results to stdout.
847 Optional arg 'verbose' controls how wordy this is. By
848 default, use the verbose setting established by the
849 constructor.
850 """
851
852 if verbose is None:
853 verbose = self.verbose
854 notests = []
855 passed = []
856 failed = []
857 totalt = totalf = 0
858 for x in self.name2ft.items():
859 name, (f, t) = x
860 assert f <= t
861 totalt = totalt + t
862 totalf = totalf + f
863 if t == 0:
864 notests.append(name)
865 elif f == 0:
866 passed.append( (name, t) )
867 else:
868 failed.append(x)
869 if verbose:
870 if notests:
871 print len(notests), "items had no tests:"
872 notests.sort()
873 for thing in notests:
874 print " ", thing
875 if passed:
876 print len(passed), "items passed all tests:"
877 passed.sort()
878 for thing, count in passed:
879 print " %3d tests in %s" % (count, thing)
880 if failed:
881 print len(failed), "items had failures:"
882 failed.sort()
883 for thing, (f, t) in failed:
884 print " %3d of %3d in %s" % (f, t, thing)
885 if verbose:
886 print totalt, "tests in", len(self.name2ft), "items."
887 print totalt - totalf, "passed and", totalf, "failed."
888 if totalf:
889 print "***Test Failed***", totalf, "failures."
890 elif verbose:
891 print "Test passed."
892 return totalf, totalt
893
894 def merge(self, other):
895 """
896 other -> merge in test results from the other Tester instance.
897
898 If self and other both have a test result for something
899 with the same name, the (#failures, #tests) results are
900 summed, and a warning is printed to stdout.
901
902 >>> from doctest import Tester
903 >>> t1 = Tester(globs={}, verbose=0)
904 >>> t1.runstring('''
905 ... >>> x = 12
906 ... >>> print x
907 ... 12
908 ... ''', "t1example")
909 (0, 2)
910 >>>
911 >>> t2 = Tester(globs={}, verbose=0)
912 >>> t2.runstring('''
913 ... >>> x = 13
914 ... >>> print x
915 ... 13
916 ... ''', "t2example")
917 (0, 2)
918 >>> common = ">>> assert 1 + 2 == 3\\n"
919 >>> t1.runstring(common, "common")
920 (0, 1)
921 >>> t2.runstring(common, "common")
922 (0, 1)
923 >>> t1.merge(t2)
924 *** Tester.merge: 'common' in both testers; summing outcomes.
925 >>> t1.summarize(1)
926 3 items passed all tests:
927 2 tests in common
928 2 tests in t1example
929 2 tests in t2example
930 6 tests in 3 items.
931 6 passed and 0 failed.
932 Test passed.
933 (0, 6)
934 >>>
935 """
936
937 d = self.name2ft
938 for name, (f, t) in other.name2ft.items():
939 if d.has_key(name):
940 print "*** Tester.merge: '" + name + "' in both" \
941 " testers; summing outcomes."
942 f2, t2 = d[name]
943 f = f + f2
944 t = t + t2
945 d[name] = f, t
946
947 def __record_outcome(self, name, f, t):
948 if self.name2ft.has_key(name):
949 print "*** Warning: '" + name + "' was tested before;", \
950 "summing outcomes."
951 f2, t2 = self.name2ft[name]
952 f = f + f2
953 t = t + t2
954 self.name2ft[name] = f, t
955
956 def __runone(self, target, name):
957 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000958 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000959 prefix, base = name[:i], name[i+1:]
960 else:
961 prefix, base = "", base
962 if self.isprivate(prefix, base):
963 return 0, 0
964 return self.rundoc(target, name)
965
966master = None
967
968def testmod(m, name=None, globs=None, verbose=None, isprivate=None,
969 report=1):
970 """m, name=None, globs=None, verbose=None, isprivate=None, report=1
971
972 Test examples in docstrings in functions and classes reachable from
973 module m, starting with m.__doc__. Private names are skipped.
974
975 Also test examples reachable from dict m.__test__ if it exists and is
976 not None. m.__dict__ maps names to functions, classes and strings;
977 function and class docstrings are tested even if the name is private;
978 strings are tested directly, as if they were docstrings.
979
980 Return (#failures, #tests).
981
982 See doctest.__doc__ for an overview.
983
984 Optional keyword arg "name" gives the name of the module; by default
985 use m.__name__.
986
987 Optional keyword arg "globs" gives a dict to be used as the globals
988 when executing examples; by default, use m.__dict__. A copy of this
989 dict is actually used for each docstring, so that each docstring's
990 examples start with a clean slate.
991
992 Optional keyword arg "verbose" prints lots of stuff if true, prints
993 only failures if false; by default, it's true iff "-v" is in sys.argv.
994
995 Optional keyword arg "isprivate" specifies a function used to
996 determine whether a name is private. The default function is
997 doctest.is_private; see its docs for details.
998
999 Optional keyword arg "report" prints a summary at the end when true,
1000 else prints nothing at the end. In verbose mode, the summary is
1001 detailed, else very brief (in fact, empty if all tests passed).
1002
1003 Advanced tomfoolery: testmod runs methods of a local instance of
1004 class doctest.Tester, then merges the results into (or creates)
1005 global Tester instance doctest.master. Methods of doctest.master
1006 can be called directly too, if you want to do something unusual.
1007 Passing report=0 to testmod is especially useful then, to delay
1008 displaying a summary. Invoke doctest.master.summarize(verbose)
1009 when you're done fiddling.
1010 """
1011
1012 global master
1013
1014 if type(m) is not _ModuleType:
1015 raise TypeError("testmod: module required; " + `m`)
1016 if name is None:
1017 name = m.__name__
1018 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate)
1019 failures, tries = tester.rundoc(m, name)
1020 f, t = tester.rundict(m.__dict__, name)
1021 failures = failures + f
1022 tries = tries + t
1023 if hasattr(m, "__test__"):
1024 testdict = m.__test__
1025 if testdict:
1026 if not hasattr(testdict, "items"):
1027 raise TypeError("testmod: module.__test__ must support "
1028 ".items(); " + `testdict`)
1029 f, t = tester.run__test__(testdict, name + ".__test__")
1030 failures = failures + f
1031 tries = tries + t
1032 if report:
1033 tester.summarize()
1034 if master is None:
1035 master = tester
1036 else:
1037 master.merge(tester)
1038 return failures, tries
1039
1040class _TestClass:
1041 """
1042 A pointless class, for sanity-checking of docstring testing.
1043
1044 Methods:
1045 square()
1046 get()
1047
1048 >>> _TestClass(13).get() + _TestClass(-12).get()
1049 1
1050 >>> hex(_TestClass(13).square().get())
1051 '0xa9'
1052 """
1053
1054 def __init__(self, val):
1055 """val -> _TestClass object with associated value val.
1056
1057 >>> t = _TestClass(123)
1058 >>> print t.get()
1059 123
1060 """
1061
1062 self.val = val
1063
1064 def square(self):
1065 """square() -> square TestClass's associated value
1066
1067 >>> _TestClass(13).square().get()
1068 169
1069 """
1070
1071 self.val = self.val ** 2
1072 return self
1073
1074 def get(self):
1075 """get() -> return TestClass's associated value.
1076
1077 >>> x = _TestClass(-42)
1078 >>> print x.get()
1079 -42
1080 """
1081
1082 return self.val
1083
1084__test__ = {"_TestClass": _TestClass,
1085 "string": r"""
1086 Example of a string object, searched as-is.
1087 >>> x = 1; y = 2
1088 >>> x + y, x * y
1089 (3, 2)
1090 """
1091 }
1092
1093def _test():
1094 import doctest
1095 return doctest.testmod(doctest)
1096
1097if __name__ == "__main__":
1098 _test()