Fix sf bug 666219: assertion error in httplib.
[python/dscho.git] / Lib / doctest.py
blob55f15f11378fac8e5cf54ce24aafa0ed32878b09
1 # Module doctest.
2 # Released to the public domain 16-Jan-2001,
3 # by Tim Peters (tim.one@home.com).
5 # Provided as-is; use at your own risk; no warranty; no promises; enjoy!
7 """Module doctest -- a framework for running examples in docstrings.
9 NORMAL USAGE
11 In normal use, end each module M with:
13 def _test():
14 import doctest, M # replace M with your module's name
15 return doctest.testmod(M) # ditto
17 if __name__ == "__main__":
18 _test()
20 Then running the module as a script will cause the examples in the
21 docstrings to get executed and verified:
23 python M.py
25 This won't display anything unless an example fails, in which case the
26 failing example(s) and the cause(s) of the failure(s) are printed to stdout
27 (why not stderr? because stderr is a lame hack <0.2 wink>), and the final
28 line of output is "Test failed.".
30 Run it with the -v switch instead:
32 python M.py -v
34 and a detailed report of all examples tried is printed to stdout, along
35 with assorted summaries at the end.
37 You can force verbose mode by passing "verbose=1" to testmod, or prohibit
38 it by passing "verbose=0". In either of those cases, sys.argv is not
39 examined by testmod.
41 In any case, testmod returns a 2-tuple of ints (f, t), where f is the
42 number of docstring examples that failed and t is the total number of
43 docstring examples attempted.
46 WHICH DOCSTRINGS ARE EXAMINED?
48 + M.__doc__.
50 + f.__doc__ for all functions f in M.__dict__.values(), except those
51 with private names and those defined in other modules.
53 + C.__doc__ for all classes C in M.__dict__.values(), except those with
54 private names and those defined in other modules.
56 + If M.__test__ exists and "is true", it must be a dict, and
57 each entry maps a (string) name to a function object, class object, or
58 string. Function and class object docstrings found from M.__test__
59 are searched even if the name is private, and strings are searched
60 directly as if they were docstrings. In output, a key K in M.__test__
61 appears with name
62 <name of M>.__test__.K
64 Any classes found are recursively searched similarly, to test docstrings in
65 their contained methods and nested classes. Private names reached from M's
66 globals are skipped, but all names reached from M.__test__ are searched.
68 By default, a name is considered to be private if it begins with an
69 underscore (like "_my_func") but doesn't both begin and end with (at least)
70 two underscores (like "__init__"). You can change the default by passing
71 your own "isprivate" function to testmod.
73 If you want to test docstrings in objects with private names too, stuff
74 them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
75 own isprivate function to Tester's constructor, or call the rundoc method
76 of a Tester instance).
78 WHAT'S THE EXECUTION CONTEXT?
80 By default, each time testmod finds a docstring to test, it uses a *copy*
81 of M's globals (so that running tests on a module doesn't change the
82 module's real globals, and so that one test in M can't leave behind crumbs
83 that accidentally allow another test to work). This means examples can
84 freely use any names defined at top-level in M. It also means that sloppy
85 imports (see above) can cause examples in external docstrings to use
86 globals inappropriate for them.
88 You can force use of your own dict as the execution context by passing
89 "globs=your_dict" to testmod instead. Presumably this would be a copy of
90 M.__dict__ merged with the globals from other imported modules.
93 WHAT IF I WANT TO TEST A WHOLE PACKAGE?
95 Piece o' cake, provided the modules do their testing from docstrings.
96 Here's the test.py I use for the world's most elaborate Rational/
97 floating-base-conversion pkg (which I'll distribute some day):
99 from Rational import Cvt
100 from Rational import Format
101 from Rational import machprec
102 from Rational import Rat
103 from Rational import Round
104 from Rational import utils
106 modules = (Cvt,
107 Format,
108 machprec,
109 Rat,
110 Round,
111 utils)
113 def _test():
114 import doctest
115 import sys
116 verbose = "-v" in sys.argv
117 for mod in modules:
118 doctest.testmod(mod, verbose=verbose, report=0)
119 doctest.master.summarize()
121 if __name__ == "__main__":
122 _test()
124 IOW, it just runs testmod on all the pkg modules. testmod remembers the
125 names and outcomes (# of failures, # of tries) for each item it's seen, and
126 passing "report=0" prevents it from printing a summary in verbose mode.
127 Instead, the summary is delayed until all modules have been tested, and
128 then "doctest.master.summarize()" forces the summary at the end.
130 So this is very nice in practice: each module can be tested individually
131 with almost no work beyond writing up docstring examples, and collections
132 of modules can be tested too as a unit with no more work than the above.
135 WHAT ABOUT EXCEPTIONS?
137 No problem, as long as the only output generated by the example is the
138 traceback itself. For example:
140 >>> [1, 2, 3].remove(42)
141 Traceback (most recent call last):
142 File "<stdin>", line 1, in ?
143 ValueError: list.remove(x): x not in list
146 Note that only the exception type and value are compared (specifically,
147 only the last line in the traceback).
150 ADVANCED USAGE
152 doctest.testmod() captures the testing policy I find most useful most
153 often. You may want other policies.
155 testmod() actually creates a local instance of class doctest.Tester, runs
156 appropriate methods of that class, and merges the results into global
157 Tester instance doctest.master.
159 You can create your own instances of doctest.Tester, and so build your own
160 policies, or even run methods of doctest.master directly. See
161 doctest.Tester.__doc__ for details.
164 SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
166 Oh ya. It's easy! In most cases a copy-and-paste of an interactive
167 console session works fine -- just make sure the leading whitespace is
168 rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
169 right, but doctest is not in the business of guessing what you think a tab
170 means).
172 >>> # comments are ignored
173 >>> x = 12
174 >>> x
176 >>> if x == 13:
177 ... print "yes"
178 ... else:
179 ... print "no"
180 ... print "NO"
181 ... print "NO!!!"
185 NO!!!
188 Any expected output must immediately follow the final ">>>" or "..." line
189 containing the code, and the expected output (if any) extends to the next
190 ">>>" or all-whitespace line. That's it.
192 Bummers:
194 + Expected output cannot contain an all-whitespace line, since such a line
195 is taken to signal the end of expected output.
197 + Output to stdout is captured, but not output to stderr (exception
198 tracebacks are captured via a different means).
200 + If you continue a line via backslashing in an interactive session, or for
201 any other reason use a backslash, you need to double the backslash in the
202 docstring version. This is simply because you're in a string, and so the
203 backslash must be escaped for it to survive intact. Like:
205 >>> if "yes" == \\
206 ... "y" + \\
207 ... "es": # in the source code you'll see the doubled backslashes
208 ... print 'yes'
211 The starting column doesn't matter:
213 >>> assert "Easy!"
214 >>> import math
215 >>> math.floor(1.9)
218 and as many leading whitespace characters are stripped from the expected
219 output as appeared in the initial ">>>" line that triggered it.
221 If you execute this very file, the examples above will be found and
222 executed, leading to this output in verbose mode:
224 Running doctest.__doc__
225 Trying: [1, 2, 3].remove(42)
226 Expecting:
227 Traceback (most recent call last):
228 File "<stdin>", line 1, in ?
229 ValueError: list.remove(x): x not in list
231 Trying: x = 12
232 Expecting: nothing
234 Trying: x
235 Expecting: 12
237 Trying:
238 if x == 13:
239 print "yes"
240 else:
241 print "no"
242 print "NO"
243 print "NO!!!"
244 Expecting:
247 NO!!!
249 ... and a bunch more like that, with this summary at the end:
251 5 items had no tests:
252 doctest.Tester.__init__
253 doctest.Tester.run__test__
254 doctest.Tester.summarize
255 doctest.run_docstring_examples
256 doctest.testmod
257 12 items passed all tests:
258 8 tests in doctest
259 6 tests in doctest.Tester
260 10 tests in doctest.Tester.merge
261 14 tests in doctest.Tester.rundict
262 3 tests in doctest.Tester.rundoc
263 3 tests in doctest.Tester.runstring
264 2 tests in doctest.__test__._TestClass
265 2 tests in doctest.__test__._TestClass.__init__
266 2 tests in doctest.__test__._TestClass.get
267 1 tests in doctest.__test__._TestClass.square
268 2 tests in doctest.__test__.string
269 7 tests in doctest.is_private
270 60 tests in 17 items.
271 60 passed and 0 failed.
272 Test passed.
275 __all__ = [
276 'testmod',
277 'run_docstring_examples',
278 'is_private',
279 'Tester',
280 'DocTestTestFailure',
281 'DocTestSuite',
282 'testsource',
283 'debug',
286 import __future__
288 import re
289 PS1 = ">>>"
290 PS2 = "..."
291 _isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
292 _isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
293 _isEmpty = re.compile(r"\s*$").match
294 _isComment = re.compile(r"\s*#").match
295 del re
297 from types import StringTypes as _StringTypes
299 from inspect import isclass as _isclass
300 from inspect import isfunction as _isfunction
301 from inspect import ismodule as _ismodule
302 from inspect import classify_class_attrs as _classify_class_attrs
304 # Option constants.
305 DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
307 # Extract interactive examples from a string. Return a list of triples,
308 # (source, outcome, lineno). "source" is the source code, and ends
309 # with a newline iff the source spans more than one line. "outcome" is
310 # the expected output if any, else an empty string. When not empty,
311 # outcome always ends with a newline. "lineno" is the line number,
312 # 0-based wrt the start of the string, of the first source line.
314 def _extract_examples(s):
315 isPS1, isPS2 = _isPS1, _isPS2
316 isEmpty, isComment = _isEmpty, _isComment
317 examples = []
318 lines = s.split("\n")
319 i, n = 0, len(lines)
320 while i < n:
321 line = lines[i]
322 i = i + 1
323 m = isPS1(line)
324 if m is None:
325 continue
326 j = m.end(0) # beyond the prompt
327 if isEmpty(line, j) or isComment(line, j):
328 # a bare prompt or comment -- not interesting
329 continue
330 lineno = i - 1
331 if line[j] != " ":
332 raise ValueError("line " + `lineno` + " of docstring lacks "
333 "blank after " + PS1 + ": " + line)
334 j = j + 1
335 blanks = m.group(1)
336 nblanks = len(blanks)
337 # suck up this and following PS2 lines
338 source = []
339 while 1:
340 source.append(line[j:])
341 line = lines[i]
342 m = isPS2(line)
343 if m:
344 if m.group(1) != blanks:
345 raise ValueError("inconsistent leading whitespace "
346 "in line " + `i` + " of docstring: " + line)
347 i = i + 1
348 else:
349 break
350 if len(source) == 1:
351 source = source[0]
352 else:
353 # get rid of useless null line from trailing empty "..."
354 if source[-1] == "":
355 del source[-1]
356 source = "\n".join(source) + "\n"
357 # suck up response
358 if isPS1(line) or isEmpty(line):
359 expect = ""
360 else:
361 expect = []
362 while 1:
363 if line[:nblanks] != blanks:
364 raise ValueError("inconsistent leading whitespace "
365 "in line " + `i` + " of docstring: " + line)
366 expect.append(line[nblanks:])
367 i = i + 1
368 line = lines[i]
369 if isPS1(line) or isEmpty(line):
370 break
371 expect = "\n".join(expect) + "\n"
372 examples.append( (source, expect, lineno) )
373 return examples
375 # Capture stdout when running examples.
377 class _SpoofOut:
378 def __init__(self):
379 self.clear()
380 def write(self, s):
381 self.buf.append(s)
382 def get(self):
383 guts = "".join(self.buf)
384 # If anything at all was written, make sure there's a trailing
385 # newline. There's no way for the expected output to indicate
386 # that a trailing newline is missing.
387 if guts and not guts.endswith("\n"):
388 guts = guts + "\n"
389 # Prevent softspace from screwing up the next test case, in
390 # case they used print with a trailing comma in an example.
391 if hasattr(self, "softspace"):
392 del self.softspace
393 return guts
394 def clear(self):
395 self.buf = []
396 if hasattr(self, "softspace"):
397 del self.softspace
398 def flush(self):
399 # JPython calls flush
400 pass
402 # Display some tag-and-msg pairs nicely, keeping the tag and its msg
403 # on the same line when that makes sense.
405 def _tag_out(printer, *tag_msg_pairs):
406 for tag, msg in tag_msg_pairs:
407 printer(tag + ":")
408 msg_has_nl = msg[-1:] == "\n"
409 msg_has_two_nl = msg_has_nl and \
410 msg.find("\n") < len(msg) - 1
411 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
412 printer(" ")
413 else:
414 printer("\n")
415 printer(msg)
416 if not msg_has_nl:
417 printer("\n")
419 # Run list of examples, in context globs. "out" can be used to display
420 # stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
421 # that captures the examples' std output. Return (#failures, #tries).
423 def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
424 compileflags, optionflags):
425 import sys, traceback
426 OK, BOOM, FAIL = range(3)
427 NADA = "nothing"
428 stderr = _SpoofOut()
429 failures = 0
430 for source, want, lineno in examples:
431 if verbose:
432 _tag_out(out, ("Trying", source),
433 ("Expecting", want or NADA))
434 fakeout.clear()
435 try:
436 exec compile(source, "<string>", "single",
437 compileflags, 1) in globs
438 got = fakeout.get()
439 state = OK
440 except KeyboardInterrupt:
441 raise
442 except:
443 # See whether the exception was expected.
444 if want.find("Traceback (innermost last):\n") == 0 or \
445 want.find("Traceback (most recent call last):\n") == 0:
446 # Only compare exception type and value - the rest of
447 # the traceback isn't necessary.
448 want = want.split('\n')[-2] + '\n'
449 exc_type, exc_val = sys.exc_info()[:2]
450 got = traceback.format_exception_only(exc_type, exc_val)[-1]
451 state = OK
452 else:
453 # unexpected exception
454 stderr.clear()
455 traceback.print_exc(file=stderr)
456 state = BOOM
458 if state == OK:
459 if (got == want or
460 (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and
461 (got, want) in (("True\n", "1\n"), ("False\n", "0\n"))
464 if verbose:
465 out("ok\n")
466 continue
467 state = FAIL
469 assert state in (FAIL, BOOM)
470 failures = failures + 1
471 out("*" * 65 + "\n")
472 _tag_out(out, ("Failure in example", source))
473 out("from line #" + `lineno` + " of " + name + "\n")
474 if state == FAIL:
475 _tag_out(out, ("Expected", want or NADA), ("Got", got))
476 else:
477 assert state == BOOM
478 _tag_out(out, ("Exception raised", stderr.get()))
480 return failures, len(examples)
482 # Get the future-flags associated with the future features that have been
483 # imported into globs.
485 def _extract_future_flags(globs):
486 flags = 0
487 for fname in __future__.all_feature_names:
488 feature = globs.get(fname, None)
489 if feature is getattr(__future__, fname):
490 flags |= feature.compiler_flag
491 return flags
493 # Run list of examples, in a shallow copy of context (dict) globs.
494 # Return (#failures, #tries).
496 def _run_examples(examples, globs, verbose, name, compileflags,
497 optionflags):
498 import sys
499 saveout = sys.stdout
500 globs = globs.copy()
501 try:
502 sys.stdout = fakeout = _SpoofOut()
503 x = _run_examples_inner(saveout.write, fakeout, examples,
504 globs, verbose, name, compileflags,
505 optionflags)
506 finally:
507 sys.stdout = saveout
508 # While Python gc can clean up most cycles on its own, it doesn't
509 # chase frame objects. This is especially irksome when running
510 # generator tests that raise exceptions, because a named generator-
511 # iterator gets an entry in globs, and the generator-iterator
512 # object's frame's traceback info points back to globs. This is
513 # easy to break just by clearing the namespace. This can also
514 # help to break other kinds of cycles, and even for cycles that
515 # gc can break itself it's better to break them ASAP.
516 globs.clear()
517 return x
519 def run_docstring_examples(f, globs, verbose=0, name="NoName",
520 compileflags=None, optionflags=0):
521 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
523 Use (a shallow copy of) dict globs as the globals for execution.
524 Return (#failures, #tries).
526 If optional arg verbose is true, print stuff even if there are no
527 failures.
528 Use string name in failure msgs.
531 try:
532 doc = f.__doc__
533 if not doc:
534 # docstring empty or None
535 return 0, 0
536 # just in case CT invents a doc object that has to be forced
537 # to look like a string <0.9 wink>
538 doc = str(doc)
539 except KeyboardInterrupt:
540 raise
541 except:
542 return 0, 0
544 e = _extract_examples(doc)
545 if not e:
546 return 0, 0
547 if compileflags is None:
548 compileflags = _extract_future_flags(globs)
549 return _run_examples(e, globs, verbose, name, compileflags, optionflags)
551 def is_private(prefix, base):
552 """prefix, base -> true iff name prefix + "." + base is "private".
554 Prefix may be an empty string, and base does not contain a period.
555 Prefix is ignored (although functions you write conforming to this
556 protocol may make use of it).
557 Return true iff base begins with an (at least one) underscore, but
558 does not both begin and end with (at least) two underscores.
560 >>> is_private("a.b", "my_func")
561 False
562 >>> is_private("____", "_my_func")
563 True
564 >>> is_private("someclass", "__init__")
565 False
566 >>> is_private("sometypo", "__init_")
567 True
568 >>> is_private("x.y.z", "_")
569 True
570 >>> is_private("_x.y.z", "__")
571 False
572 >>> is_private("", "") # senseless but consistent
573 False
576 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
578 # Determine if a class of function was defined in the given module.
580 def _from_module(module, object):
581 if _isfunction(object):
582 return module.__dict__ is object.func_globals
583 if _isclass(object):
584 return module.__name__ == object.__module__
585 raise ValueError("object must be a class or function")
587 class Tester:
588 """Class Tester -- runs docstring examples and accumulates stats.
590 In normal use, function doctest.testmod() hides all this from you,
591 so use that if you can. Create your own instances of Tester to do
592 fancier things.
594 Methods:
595 runstring(s, name)
596 Search string s for examples to run; use name for logging.
597 Return (#failures, #tries).
599 rundoc(object, name=None)
600 Search object.__doc__ for examples to run; use name (or
601 object.__name__) for logging. Return (#failures, #tries).
603 rundict(d, name, module=None)
604 Search for examples in docstrings in all of d.values(); use name
605 for logging. Exclude functions and classes not defined in module
606 if specified. Return (#failures, #tries).
608 run__test__(d, name)
609 Treat dict d like module.__test__. Return (#failures, #tries).
611 summarize(verbose=None)
612 Display summary of testing results, to stdout. Return
613 (#failures, #tries).
615 merge(other)
616 Merge in the test results from Tester instance "other".
618 >>> from doctest import Tester
619 >>> t = Tester(globs={'x': 42}, verbose=0)
620 >>> t.runstring(r'''
621 ... >>> x = x * 2
622 ... >>> print x
623 ... 42
624 ... ''', 'XYZ')
625 *****************************************************************
626 Failure in example: print x
627 from line #2 of XYZ
628 Expected: 42
629 Got: 84
630 (1, 2)
631 >>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
632 (0, 2)
633 >>> t.summarize()
634 *****************************************************************
635 1 items had failures:
636 1 of 2 in XYZ
637 ***Test Failed*** 1 failures.
638 (1, 4)
639 >>> t.summarize(verbose=1)
640 1 items passed all tests:
641 2 tests in example2
642 *****************************************************************
643 1 items had failures:
644 1 of 2 in XYZ
645 4 tests in 2 items.
646 3 passed and 1 failed.
647 ***Test Failed*** 1 failures.
648 (1, 4)
652 def __init__(self, mod=None, globs=None, verbose=None,
653 isprivate=None, optionflags=0):
654 """mod=None, globs=None, verbose=None, isprivate=None,
655 optionflags=0
657 See doctest.__doc__ for an overview.
659 Optional keyword arg "mod" is a module, whose globals are used for
660 executing examples. If not specified, globs must be specified.
662 Optional keyword arg "globs" gives a dict to be used as the globals
663 when executing examples; if not specified, use the globals from
664 module mod.
666 In either case, a copy of the dict is used for each docstring
667 examined.
669 Optional keyword arg "verbose" prints lots of stuff if true, only
670 failures if false; by default, it's true iff "-v" is in sys.argv.
672 Optional keyword arg "isprivate" specifies a function used to determine
673 whether a name is private. The default function is doctest.is_private;
674 see its docs for details.
676 See doctest.testmod docs for the meaning of optionflags.
679 if mod is None and globs is None:
680 raise TypeError("Tester.__init__: must specify mod or globs")
681 if mod is not None and not _ismodule(mod):
682 raise TypeError("Tester.__init__: mod must be a module; " +
683 `mod`)
684 if globs is None:
685 globs = mod.__dict__
686 self.globs = globs
688 if verbose is None:
689 import sys
690 verbose = "-v" in sys.argv
691 self.verbose = verbose
693 if isprivate is None:
694 isprivate = is_private
695 self.isprivate = isprivate
697 self.optionflags = optionflags
699 self.name2ft = {} # map name to (#failures, #trials) pair
701 self.compileflags = _extract_future_flags(globs)
703 def runstring(self, s, name):
705 s, name -> search string s for examples to run, logging as name.
707 Use string name as the key for logging the outcome.
708 Return (#failures, #examples).
710 >>> t = Tester(globs={}, verbose=1)
711 >>> test = r'''
712 ... # just an example
713 ... >>> x = 1 + 2
714 ... >>> x
715 ... 3
716 ... '''
717 >>> t.runstring(test, "Example")
718 Running string Example
719 Trying: x = 1 + 2
720 Expecting: nothing
722 Trying: x
723 Expecting: 3
725 0 of 2 examples failed in string Example
726 (0, 2)
729 if self.verbose:
730 print "Running string", name
731 f = t = 0
732 e = _extract_examples(s)
733 if e:
734 f, t = _run_examples(e, self.globs, self.verbose, name,
735 self.compileflags, self.optionflags)
736 if self.verbose:
737 print f, "of", t, "examples failed in string", name
738 self.__record_outcome(name, f, t)
739 return f, t
741 def rundoc(self, object, name=None):
743 object, name=None -> search object.__doc__ for examples to run.
745 Use optional string name as the key for logging the outcome;
746 by default use object.__name__.
747 Return (#failures, #examples).
748 If object is a class object, search recursively for method
749 docstrings too.
750 object.__doc__ is examined regardless of name, but if object is
751 a class, whether private names reached from object are searched
752 depends on the constructor's "isprivate" argument.
754 >>> t = Tester(globs={}, verbose=0)
755 >>> def _f():
756 ... '''Trivial docstring example.
757 ... >>> assert 2 == 2
758 ... '''
759 ... return 32
761 >>> t.rundoc(_f) # expect 0 failures in 1 example
762 (0, 1)
765 if name is None:
766 try:
767 name = object.__name__
768 except AttributeError:
769 raise ValueError("Tester.rundoc: name must be given "
770 "when object.__name__ doesn't exist; " + `object`)
771 if self.verbose:
772 print "Running", name + ".__doc__"
773 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
774 self.compileflags, self.optionflags)
775 if self.verbose:
776 print f, "of", t, "examples failed in", name + ".__doc__"
777 self.__record_outcome(name, f, t)
778 if _isclass(object):
779 # In 2.2, class and static methods complicate life. Build
780 # a dict "that works", by hook or by crook.
781 d = {}
782 for tag, kind, homecls, value in _classify_class_attrs(object):
784 if homecls is not object:
785 # Only look at names defined immediately by the class.
786 continue
788 elif self.isprivate(name, tag):
789 continue
791 elif kind == "method":
792 # value is already a function
793 d[tag] = value
795 elif kind == "static method":
796 # value isn't a function, but getattr reveals one
797 d[tag] = getattr(object, tag)
799 elif kind == "class method":
800 # Hmm. A classmethod object doesn't seem to reveal
801 # enough. But getattr turns it into a bound method,
802 # and from there .im_func retrieves the underlying
803 # function.
804 d[tag] = getattr(object, tag).im_func
806 elif kind == "property":
807 # The methods implementing the property have their
808 # own docstrings -- but the property may have one too.
809 if value.__doc__ is not None:
810 d[tag] = str(value.__doc__)
812 elif kind == "data":
813 # Grab nested classes.
814 if _isclass(value):
815 d[tag] = value
817 else:
818 raise ValueError("teach doctest about %r" % kind)
820 f2, t2 = self.run__test__(d, name)
821 f += f2
822 t += t2
824 return f, t
826 def rundict(self, d, name, module=None):
828 d, name, module=None -> search for docstring examples in d.values().
830 For k, v in d.items() such that v is a function or class,
831 do self.rundoc(v, name + "." + k). Whether this includes
832 objects with private names depends on the constructor's
833 "isprivate" argument. If module is specified, functions and
834 classes that are not defined in module are excluded.
835 Return aggregate (#failures, #examples).
837 Build and populate two modules with sample functions to test that
838 exclusion of external functions and classes works.
840 >>> import new
841 >>> m1 = new.module('_m1')
842 >>> m2 = new.module('_m2')
843 >>> test_data = \"""
844 ... def _f():
845 ... '''>>> assert 1 == 1
846 ... '''
847 ... def g():
848 ... '''>>> assert 2 != 1
849 ... '''
850 ... class H:
851 ... '''>>> assert 2 > 1
852 ... '''
853 ... def bar(self):
854 ... '''>>> assert 1 < 2
855 ... '''
856 ... \"""
857 >>> exec test_data in m1.__dict__
858 >>> exec test_data in m2.__dict__
859 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
861 Tests that objects outside m1 are excluded:
863 >>> t = Tester(globs={}, verbose=0)
864 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
865 (0, 3)
867 Again, but with a custom isprivate function allowing _f:
869 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
870 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
871 (0, 4)
873 And once more, not excluding stuff outside m1:
875 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
876 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
877 (0, 8)
879 The exclusion of objects from outside the designated module is
880 meant to be invoked automagically by testmod.
882 >>> testmod(m1)
883 (0, 3)
887 if not hasattr(d, "items"):
888 raise TypeError("Tester.rundict: d must support .items(); " +
889 `d`)
890 f = t = 0
891 # Run the tests by alpha order of names, for consistency in
892 # verbose-mode output.
893 names = d.keys()
894 names.sort()
895 for thisname in names:
896 value = d[thisname]
897 if _isfunction(value) or _isclass(value):
898 if module and not _from_module(module, value):
899 continue
900 f2, t2 = self.__runone(value, name + "." + thisname)
901 f = f + f2
902 t = t + t2
903 return f, t
905 def run__test__(self, d, name):
906 """d, name -> Treat dict d like module.__test__.
908 Return (#failures, #tries).
909 See testmod.__doc__ for details.
912 failures = tries = 0
913 prefix = name + "."
914 savepvt = self.isprivate
915 try:
916 self.isprivate = lambda *args: 0
917 # Run the tests by alpha order of names, for consistency in
918 # verbose-mode output.
919 keys = d.keys()
920 keys.sort()
921 for k in keys:
922 v = d[k]
923 thisname = prefix + k
924 if type(v) in _StringTypes:
925 f, t = self.runstring(v, thisname)
926 elif _isfunction(v) or _isclass(v):
927 f, t = self.rundoc(v, thisname)
928 else:
929 raise TypeError("Tester.run__test__: values in "
930 "dict must be strings, functions "
931 "or classes; " + `v`)
932 failures = failures + f
933 tries = tries + t
934 finally:
935 self.isprivate = savepvt
936 return failures, tries
938 def summarize(self, verbose=None):
940 verbose=None -> summarize results, return (#failures, #tests).
942 Print summary of test results to stdout.
943 Optional arg 'verbose' controls how wordy this is. By
944 default, use the verbose setting established by the
945 constructor.
948 if verbose is None:
949 verbose = self.verbose
950 notests = []
951 passed = []
952 failed = []
953 totalt = totalf = 0
954 for x in self.name2ft.items():
955 name, (f, t) = x
956 assert f <= t
957 totalt = totalt + t
958 totalf = totalf + f
959 if t == 0:
960 notests.append(name)
961 elif f == 0:
962 passed.append( (name, t) )
963 else:
964 failed.append(x)
965 if verbose:
966 if notests:
967 print len(notests), "items had no tests:"
968 notests.sort()
969 for thing in notests:
970 print " ", thing
971 if passed:
972 print len(passed), "items passed all tests:"
973 passed.sort()
974 for thing, count in passed:
975 print " %3d tests in %s" % (count, thing)
976 if failed:
977 print "*" * 65
978 print len(failed), "items had failures:"
979 failed.sort()
980 for thing, (f, t) in failed:
981 print " %3d of %3d in %s" % (f, t, thing)
982 if verbose:
983 print totalt, "tests in", len(self.name2ft), "items."
984 print totalt - totalf, "passed and", totalf, "failed."
985 if totalf:
986 print "***Test Failed***", totalf, "failures."
987 elif verbose:
988 print "Test passed."
989 return totalf, totalt
991 def merge(self, other):
993 other -> merge in test results from the other Tester instance.
995 If self and other both have a test result for something
996 with the same name, the (#failures, #tests) results are
997 summed, and a warning is printed to stdout.
999 >>> from doctest import Tester
1000 >>> t1 = Tester(globs={}, verbose=0)
1001 >>> t1.runstring('''
1002 ... >>> x = 12
1003 ... >>> print x
1004 ... 12
1005 ... ''', "t1example")
1006 (0, 2)
1008 >>> t2 = Tester(globs={}, verbose=0)
1009 >>> t2.runstring('''
1010 ... >>> x = 13
1011 ... >>> print x
1012 ... 13
1013 ... ''', "t2example")
1014 (0, 2)
1015 >>> common = ">>> assert 1 + 2 == 3\\n"
1016 >>> t1.runstring(common, "common")
1017 (0, 1)
1018 >>> t2.runstring(common, "common")
1019 (0, 1)
1020 >>> t1.merge(t2)
1021 *** Tester.merge: 'common' in both testers; summing outcomes.
1022 >>> t1.summarize(1)
1023 3 items passed all tests:
1024 2 tests in common
1025 2 tests in t1example
1026 2 tests in t2example
1027 6 tests in 3 items.
1028 6 passed and 0 failed.
1029 Test passed.
1030 (0, 6)
1034 d = self.name2ft
1035 for name, (f, t) in other.name2ft.items():
1036 if name in d:
1037 print "*** Tester.merge: '" + name + "' in both" \
1038 " testers; summing outcomes."
1039 f2, t2 = d[name]
1040 f = f + f2
1041 t = t + t2
1042 d[name] = f, t
1044 def __record_outcome(self, name, f, t):
1045 if name in self.name2ft:
1046 print "*** Warning: '" + name + "' was tested before;", \
1047 "summing outcomes."
1048 f2, t2 = self.name2ft[name]
1049 f = f + f2
1050 t = t + t2
1051 self.name2ft[name] = f, t
1053 def __runone(self, target, name):
1054 if "." in name:
1055 i = name.rindex(".")
1056 prefix, base = name[:i], name[i+1:]
1057 else:
1058 prefix, base = "", base
1059 if self.isprivate(prefix, base):
1060 return 0, 0
1061 return self.rundoc(target, name)
1063 master = None
1065 def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
1066 report=True, optionflags=0):
1067 """m=None, name=None, globs=None, verbose=None, isprivate=None,
1068 report=True, optionflags=0
1070 Test examples in docstrings in functions and classes reachable
1071 from module m (or the current module if m is not supplied), starting
1072 with m.__doc__. Private names are skipped.
1074 Also test examples reachable from dict m.__test__ if it exists and is
1075 not None. m.__dict__ maps names to functions, classes and strings;
1076 function and class docstrings are tested even if the name is private;
1077 strings are tested directly, as if they were docstrings.
1079 Return (#failures, #tests).
1081 See doctest.__doc__ for an overview.
1083 Optional keyword arg "name" gives the name of the module; by default
1084 use m.__name__.
1086 Optional keyword arg "globs" gives a dict to be used as the globals
1087 when executing examples; by default, use m.__dict__. A copy of this
1088 dict is actually used for each docstring, so that each docstring's
1089 examples start with a clean slate.
1091 Optional keyword arg "verbose" prints lots of stuff if true, prints
1092 only failures if false; by default, it's true iff "-v" is in sys.argv.
1094 Optional keyword arg "isprivate" specifies a function used to
1095 determine whether a name is private. The default function is
1096 doctest.is_private; see its docs for details.
1098 Optional keyword arg "report" prints a summary at the end when true,
1099 else prints nothing at the end. In verbose mode, the summary is
1100 detailed, else very brief (in fact, empty if all tests passed).
1102 Optional keyword arg "optionflags" or's together module constants,
1103 and defaults to 0. This is new in 2.3. Possible values:
1105 DONT_ACCEPT_TRUE_FOR_1
1106 By default, if an expected output block contains just "1",
1107 an actual output block containing just "True" is considered
1108 to be a match, and similarly for "0" versus "False". When
1109 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1110 is allowed.
1112 Advanced tomfoolery: testmod runs methods of a local instance of
1113 class doctest.Tester, then merges the results into (or creates)
1114 global Tester instance doctest.master. Methods of doctest.master
1115 can be called directly too, if you want to do something unusual.
1116 Passing report=0 to testmod is especially useful then, to delay
1117 displaying a summary. Invoke doctest.master.summarize(verbose)
1118 when you're done fiddling.
1121 global master
1123 if m is None:
1124 import sys
1125 # DWA - m will still be None if this wasn't invoked from the command
1126 # line, in which case the following TypeError is about as good an error
1127 # as we should expect
1128 m = sys.modules.get('__main__')
1130 if not _ismodule(m):
1131 raise TypeError("testmod: module required; " + `m`)
1132 if name is None:
1133 name = m.__name__
1134 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
1135 optionflags=optionflags)
1136 failures, tries = tester.rundoc(m, name)
1137 f, t = tester.rundict(m.__dict__, name, m)
1138 failures += f
1139 tries += t
1140 if hasattr(m, "__test__"):
1141 testdict = m.__test__
1142 if testdict:
1143 if not hasattr(testdict, "items"):
1144 raise TypeError("testmod: module.__test__ must support "
1145 ".items(); " + `testdict`)
1146 f, t = tester.run__test__(testdict, name + ".__test__")
1147 failures += f
1148 tries += t
1149 if report:
1150 tester.summarize()
1151 if master is None:
1152 master = tester
1153 else:
1154 master.merge(tester)
1155 return failures, tries
1157 ###########################################################################
1158 # Various doctest extensions, to make using doctest with unittest
1159 # easier, and to help debugging when a doctest goes wrong. Original
1160 # code by Jim Fulton.
1162 # Utilities.
1164 # If module is None, return the calling module (the module that called
1165 # the routine that called _normalize_module -- this normally won't be
1166 # doctest!). If module is a string, it should be the (possibly dotted)
1167 # name of a module, and the (rightmost) module object is returned. Else
1168 # module is returned untouched; the intent appears to be that module is
1169 # already a module object in this case (although this isn't checked).
1171 def _normalize_module(module):
1172 import sys
1174 if module is None:
1175 # Get our caller's caller's module.
1176 module = sys._getframe(2).f_globals['__name__']
1177 module = sys.modules[module]
1179 elif isinstance(module, (str, unicode)):
1180 # The ["*"] at the end is a mostly meaningless incantation with
1181 # a crucial property: if, e.g., module is 'a.b.c', it convinces
1182 # __import__ to return c instead of a.
1183 module = __import__(module, globals(), locals(), ["*"])
1185 return module
1187 # tests is a list of (testname, docstring, filename, lineno) tuples.
1188 # If object has a __doc__ attr, and the __doc__ attr looks like it
1189 # contains a doctest (specifically, if it contains an instance of '>>>'),
1190 # then tuple
1191 # prefix + name, object.__doc__, filename, lineno
1192 # is appended to tests. Else tests is left alone.
1193 # There is no return value.
1195 def _get_doctest(name, object, tests, prefix, filename='', lineno=''):
1196 doc = getattr(object, '__doc__', '')
1197 if isinstance(doc, basestring) and '>>>' in doc:
1198 tests.append((prefix + name, doc, filename, lineno))
1200 # tests is a list of (testname, docstring, filename, lineno) tuples.
1201 # docstrings containing doctests are appended to tests (if any are found).
1202 # items is a dict, like a module or class dict, mapping strings to objects.
1203 # mdict is the global dict of a "home" module -- only objects belonging
1204 # to this module are searched for docstrings. module is the module to
1205 # which mdict belongs.
1206 # prefix is a string to be prepended to an object's name when adding a
1207 # tuple to tests.
1208 # The objects (values) in items are examined (recursively), and doctests
1209 # belonging to functions and classes in the home module are appended to
1210 # tests.
1211 # minlineno is a gimmick to try to guess the file-relative line number
1212 # at which a doctest probably begins.
1214 def _extract_doctests(items, module, mdict, tests, prefix, minlineno=0):
1216 for name, object in items:
1217 # Only interested in named objects.
1218 if not hasattr(object, '__name__'):
1219 continue
1221 elif hasattr(object, 'func_globals'):
1222 # Looks like a function.
1223 if object.func_globals is not mdict:
1224 # Non-local function.
1225 continue
1226 code = getattr(object, 'func_code', None)
1227 filename = getattr(code, 'co_filename', '')
1228 lineno = getattr(code, 'co_firstlineno', -1) + 1
1229 if minlineno:
1230 minlineno = min(lineno, minlineno)
1231 else:
1232 minlineno = lineno
1233 _get_doctest(name, object, tests, prefix, filename, lineno)
1235 elif hasattr(object, "__module__"):
1236 # Maybe a class-like thing, in which case we care.
1237 if object.__module__ != module.__name__:
1238 # Not the same module.
1239 continue
1240 if not (hasattr(object, '__dict__')
1241 and hasattr(object, '__bases__')):
1242 # Not a class.
1243 continue
1245 lineno = _extract_doctests(object.__dict__.items(),
1246 module,
1247 mdict,
1248 tests,
1249 prefix + name + ".")
1250 # XXX "-3" is unclear.
1251 _get_doctest(name, object, tests, prefix,
1252 lineno="%s (or above)" % (lineno - 3))
1254 return minlineno
1256 # Find all the doctests belonging to the module object.
1257 # Return a list of
1258 # (testname, docstring, filename, lineno)
1259 # tuples.
1261 def _find_tests(module, prefix=None):
1262 if prefix is None:
1263 prefix = module.__name__
1264 mdict = module.__dict__
1265 tests = []
1266 # Get the module-level doctest (if any).
1267 _get_doctest(prefix, module, tests, '', lineno="1 (or above)")
1268 # Recursively search the module __dict__ for doctests.
1269 if prefix:
1270 prefix += "."
1271 _extract_doctests(mdict.items(), module, mdict, tests, prefix)
1272 return tests
1274 # unittest helpers.
1276 # A function passed to unittest, for unittest to drive.
1277 # tester is doctest Tester instance. doc is the docstring whose
1278 # doctests are to be run.
1280 def _utest(tester, name, doc, filename, lineno):
1281 import sys
1282 from StringIO import StringIO
1284 old = sys.stdout
1285 sys.stdout = new = StringIO()
1286 try:
1287 failures, tries = tester.runstring(doc, name)
1288 finally:
1289 sys.stdout = old
1291 if failures:
1292 msg = new.getvalue()
1293 lname = '.'.join(name.split('.')[-1:])
1294 if not lineno:
1295 lineno = "0 (don't know line number)"
1296 # Don't change this format! It was designed so that Emacs can
1297 # parse it naturally.
1298 raise DocTestTestFailure('Failed doctest test for %s\n'
1299 ' File "%s", line %s, in %s\n\n%s' %
1300 (name, filename, lineno, lname, msg))
1302 class DocTestTestFailure(Exception):
1303 """A doctest test failed"""
1305 def DocTestSuite(module=None):
1306 """Convert doctest tests for a module to a unittest TestSuite.
1308 The returned TestSuite is to be run by the unittest framework, and
1309 runs each doctest in the module. If any of the doctests fail,
1310 then the synthesized unit test fails, and an error is raised showing
1311 the name of the file containing the test and a (sometimes approximate)
1312 line number.
1314 The optional module argument provides the module to be tested. It
1315 can be a module object or a (possibly dotted) module name. If not
1316 specified, the module calling DocTestSuite() is used.
1318 Example (although note that unittest supplies many ways to use the
1319 TestSuite returned; see the unittest docs):
1321 import unittest
1322 import doctest
1323 import my_module_with_doctests
1325 suite = doctest.DocTestSuite(my_module_with_doctests)
1326 runner = unittest.TextTestRunner()
1327 runner.run(suite)
1330 import unittest
1332 module = _normalize_module(module)
1333 tests = _find_tests(module)
1334 if not tests:
1335 raise ValueError(module, "has no tests")
1337 tests.sort()
1338 suite = unittest.TestSuite()
1339 tester = Tester(module)
1340 for name, doc, filename, lineno in tests:
1341 if not filename:
1342 filename = module.__file__
1343 if filename.endswith(".pyc"):
1344 filename = filename[:-1]
1345 elif filename.endswith(".pyo"):
1346 filename = filename[:-1]
1347 def runit(name=name, doc=doc, filename=filename, lineno=lineno):
1348 _utest(tester, name, doc, filename, lineno)
1349 suite.addTest(unittest.FunctionTestCase(
1350 runit,
1351 description="doctest of " + name))
1352 return suite
1354 # Debugging support.
1356 def _expect(expect):
1357 # Return the expected output (if any), formatted as a Python
1358 # comment block.
1359 if expect:
1360 expect = "\n# ".join(expect.split("\n"))
1361 expect = "\n# Expect:\n# %s" % expect
1362 return expect
1364 def testsource(module, name):
1365 """Extract the doctest examples from a docstring.
1367 Provide the module (or dotted name of the module) containing the
1368 tests to be extracted, and the name (within the module) of the object
1369 with the docstring containing the tests to be extracted.
1371 The doctest examples are returned as a string containing Python
1372 code. The expected output blocks in the examples are converted
1373 to Python comments.
1376 module = _normalize_module(module)
1377 tests = _find_tests(module, "")
1378 test = [doc for (tname, doc, dummy, dummy) in tests
1379 if tname == name]
1380 if not test:
1381 raise ValueError(name, "not found in tests")
1382 test = test[0]
1383 examples = [source + _expect(expect)
1384 for source, expect, dummy in _extract_examples(test)]
1385 return '\n'.join(examples)
1387 def debug(module, name):
1388 """Debug a single docstring containing doctests.
1390 Provide the module (or dotted name of the module) containing the
1391 docstring to be debugged, and the name (within the module) of the
1392 object with the docstring to be debugged.
1394 The doctest examples are extracted (see function testsource()),
1395 and written to a temp file. The Python debugger (pdb) is then
1396 invoked on that file.
1399 import os
1400 import pdb
1401 import tempfile
1403 module = _normalize_module(module)
1404 testsrc = testsource(module, name)
1405 srcfilename = tempfile.mktemp("doctestdebug.py")
1406 f = file(srcfilename, 'w')
1407 f.write(testsrc)
1408 f.close()
1410 globs = {}
1411 globs.update(module.__dict__)
1412 try:
1413 # Note that %r is vital here. '%s' instead can, e.g., cause
1414 # backslashes to get treated as metacharacters on Windows.
1415 pdb.run("execfile(%r)" % srcfilename, globs, globs)
1416 finally:
1417 os.remove(srcfilename)
1421 class _TestClass:
1423 A pointless class, for sanity-checking of docstring testing.
1425 Methods:
1426 square()
1427 get()
1429 >>> _TestClass(13).get() + _TestClass(-12).get()
1431 >>> hex(_TestClass(13).square().get())
1432 '0xa9'
1435 def __init__(self, val):
1436 """val -> _TestClass object with associated value val.
1438 >>> t = _TestClass(123)
1439 >>> print t.get()
1443 self.val = val
1445 def square(self):
1446 """square() -> square TestClass's associated value
1448 >>> _TestClass(13).square().get()
1452 self.val = self.val ** 2
1453 return self
1455 def get(self):
1456 """get() -> return TestClass's associated value.
1458 >>> x = _TestClass(-42)
1459 >>> print x.get()
1463 return self.val
1465 __test__ = {"_TestClass": _TestClass,
1466 "string": r"""
1467 Example of a string object, searched as-is.
1468 >>> x = 1; y = 2
1469 >>> x + y, x * y
1470 (3, 2)
1471 """,
1472 "bool-int equivalence": r"""
1473 In 2.2, boolean expressions displayed
1474 0 or 1. By default, we still accept
1475 them. This can be disabled by passing
1476 DONT_ACCEPT_TRUE_FOR_1 to the new
1477 optionflags argument.
1478 >>> 4 == 4
1480 >>> 4 == 4
1481 True
1482 >>> 4 > 4
1484 >>> 4 > 4
1485 False
1486 """,
1489 def _test():
1490 import doctest
1491 return doctest.testmod(doctest)
1493 if __name__ == "__main__":
1494 _test()