blob: 2829f1e62317579536578bf241e930716c379c70 [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
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
Tim Peters7402f792001-10-02 03:53:41 +000051 with private names and those defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000052
53+ C.__doc__ for all classes C in M.__dict__.values(), except those with
Tim Peters7402f792001-10-02 03:53:41 +000054 private names and those defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000055
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
Tim Peters8a7d2d52001-01-16 07:10:57 +000078WHAT'S THE EXECUTION CONTEXT?
79
80By default, each time testmod finds a docstring to test, it uses a *copy*
81of M's globals (so that running tests on a module doesn't change the
82module's real globals, and so that one test in M can't leave behind crumbs
83that accidentally allow another test to work). This means examples can
84freely use any names defined at top-level in M. It also means that sloppy
85imports (see above) can cause examples in external docstrings to use
86globals inappropriate for them.
87
88You 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
90M.__dict__ merged with the globals from other imported modules.
91
92
93WHAT IF I WANT TO TEST A WHOLE PACKAGE?
94
95Piece o' cake, provided the modules do their testing from docstrings.
96Here's the test.py I use for the world's most elaborate Rational/
97floating-base-conversion pkg (which I'll distribute some day):
98
99from Rational import Cvt
100from Rational import Format
101from Rational import machprec
102from Rational import Rat
103from Rational import Round
104from Rational import utils
105
106modules = (Cvt,
107 Format,
108 machprec,
109 Rat,
110 Round,
111 utils)
112
113def _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()
120
121if __name__ == "__main__":
122 _test()
123
124IOW, it just runs testmod on all the pkg modules. testmod remembers the
125names and outcomes (# of failures, # of tries) for each item it's seen, and
126passing "report=0" prevents it from printing a summary in verbose mode.
127Instead, the summary is delayed until all modules have been tested, and
128then "doctest.master.summarize()" forces the summary at the end.
129
130So this is very nice in practice: each module can be tested individually
131with almost no work beyond writing up docstring examples, and collections
132of modules can be tested too as a unit with no more work than the above.
133
134
135WHAT ABOUT EXCEPTIONS?
136
137No problem, as long as the only output generated by the example is the
138traceback itself. For example:
139
Tim Peters60e23f42001-02-14 00:43:21 +0000140 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +0000141 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000142 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000143 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000144 >>>
145
146Note that only the exception type and value are compared (specifically,
147only the last line in the traceback).
148
149
150ADVANCED USAGE
151
152doctest.testmod() captures the testing policy I find most useful most
153often. You may want other policies.
154
155testmod() actually creates a local instance of class doctest.Tester, runs
156appropriate methods of that class, and merges the results into global
157Tester instance doctest.master.
158
159You can create your own instances of doctest.Tester, and so build your own
160policies, or even run methods of doctest.master directly. See
161doctest.Tester.__doc__ for details.
162
163
164SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
165
166Oh ya. It's easy! In most cases a copy-and-paste of an interactive
167console session works fine -- just make sure the leading whitespace is
168rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
169right, but doctest is not in the business of guessing what you think a tab
170means).
171
172 >>> # comments are ignored
173 >>> x = 12
174 >>> x
175 12
176 >>> if x == 13:
177 ... print "yes"
178 ... else:
179 ... print "no"
180 ... print "NO"
181 ... print "NO!!!"
182 ...
183 no
184 NO
185 NO!!!
186 >>>
187
188Any expected output must immediately follow the final ">>>" or "..." line
189containing the code, and the expected output (if any) extends to the next
190">>>" or all-whitespace line. That's it.
191
192Bummers:
193
194+ Expected output cannot contain an all-whitespace line, since such a line
195 is taken to signal the end of expected output.
196
197+ Output to stdout is captured, but not output to stderr (exception
198 tracebacks are captured via a different means).
199
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:
204
205>>> if "yes" == \\
206... "y" + \\
207... "es": # in the source code you'll see the doubled backslashes
208... print 'yes'
209yes
210
211The starting column doesn't matter:
212
213>>> assert "Easy!"
214 >>> import math
215 >>> math.floor(1.9)
216 1.0
217
218and as many leading whitespace characters are stripped from the expected
219output as appeared in the initial ">>>" line that triggered it.
220
221If you execute this very file, the examples above will be found and
222executed, leading to this output in verbose mode:
223
224Running doctest.__doc__
Tim Peters60e23f42001-02-14 00:43:21 +0000225Trying: [1, 2, 3].remove(42)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000226Expecting:
Tim Petersea4f9312001-02-13 20:54:42 +0000227Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000228 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000229ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000230ok
231Trying: x = 12
232Expecting: nothing
233ok
234Trying: x
235Expecting: 12
236ok
237Trying:
238if x == 13:
239 print "yes"
240else:
241 print "no"
242 print "NO"
243 print "NO!!!"
244Expecting:
245no
246NO
247NO!!!
248ok
249... and a bunch more like that, with this summary at the end:
250
2515 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
25712 items passed all tests:
258 8 tests in doctest
259 6 tests in doctest.Tester
260 10 tests in doctest.Tester.merge
Tim Peters17111f32001-10-03 04:08:26 +0000261 14 tests in doctest.Tester.rundict
Tim Peters8a7d2d52001-01-16 07:10:57 +0000262 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
Tim Peters17111f32001-10-03 04:08:26 +000027060 tests in 17 items.
27160 passed and 0 failed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000272Test passed.
273"""
274
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000275__all__ = [
276 'testmod',
277 'run_docstring_examples',
278 'is_private',
279 'Tester',
280]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000281
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000282import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000283
Tim Peters8a7d2d52001-01-16 07:10:57 +0000284import re
285PS1 = ">>>"
286PS2 = "..."
287_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
288_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
289_isEmpty = re.compile(r"\s*$").match
290_isComment = re.compile(r"\s*#").match
291del re
292
Tim Peters7402f792001-10-02 03:53:41 +0000293from types import StringTypes as _StringTypes
294
295from inspect import isclass as _isclass
296from inspect import isfunction as _isfunction
297from inspect import ismodule as _ismodule
Tim Peters17111f32001-10-03 04:08:26 +0000298from inspect import classify_class_attrs as _classify_class_attrs
Tim Peters7402f792001-10-02 03:53:41 +0000299
Tim Peters8a7d2d52001-01-16 07:10:57 +0000300# Extract interactive examples from a string. Return a list of triples,
301# (source, outcome, lineno). "source" is the source code, and ends
302# with a newline iff the source spans more than one line. "outcome" is
303# the expected output if any, else an empty string. When not empty,
304# outcome always ends with a newline. "lineno" is the line number,
305# 0-based wrt the start of the string, of the first source line.
306
307def _extract_examples(s):
308 isPS1, isPS2 = _isPS1, _isPS2
309 isEmpty, isComment = _isEmpty, _isComment
310 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000311 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000312 i, n = 0, len(lines)
313 while i < n:
314 line = lines[i]
315 i = i + 1
316 m = isPS1(line)
317 if m is None:
318 continue
319 j = m.end(0) # beyond the prompt
320 if isEmpty(line, j) or isComment(line, j):
321 # a bare prompt or comment -- not interesting
322 continue
323 lineno = i - 1
324 if line[j] != " ":
325 raise ValueError("line " + `lineno` + " of docstring lacks "
326 "blank after " + PS1 + ": " + line)
327 j = j + 1
328 blanks = m.group(1)
329 nblanks = len(blanks)
330 # suck up this and following PS2 lines
331 source = []
332 while 1:
333 source.append(line[j:])
334 line = lines[i]
335 m = isPS2(line)
336 if m:
337 if m.group(1) != blanks:
338 raise ValueError("inconsistent leading whitespace "
339 "in line " + `i` + " of docstring: " + line)
340 i = i + 1
341 else:
342 break
343 if len(source) == 1:
344 source = source[0]
345 else:
346 # get rid of useless null line from trailing empty "..."
347 if source[-1] == "":
348 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000349 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000350 # suck up response
351 if isPS1(line) or isEmpty(line):
352 expect = ""
353 else:
354 expect = []
355 while 1:
356 if line[:nblanks] != blanks:
357 raise ValueError("inconsistent leading whitespace "
358 "in line " + `i` + " of docstring: " + line)
359 expect.append(line[nblanks:])
360 i = i + 1
361 line = lines[i]
362 if isPS1(line) or isEmpty(line):
363 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000364 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000365 examples.append( (source, expect, lineno) )
366 return examples
367
368# Capture stdout when running examples.
369
370class _SpoofOut:
371 def __init__(self):
372 self.clear()
373 def write(self, s):
374 self.buf.append(s)
375 def get(self):
Tim Petersf9bb4962001-02-14 06:35:35 +0000376 guts = "".join(self.buf)
377 # If anything at all was written, make sure there's a trailing
378 # newline. There's no way for the expected output to indicate
379 # that a trailing newline is missing.
380 if guts and not guts.endswith("\n"):
381 guts = guts + "\n"
Tim Petersc77db342001-10-23 02:21:52 +0000382 # Prevent softspace from screwing up the next test case, in
383 # case they used print with a trailing comma in an example.
384 if hasattr(self, "softspace"):
385 del self.softspace
Tim Petersf9bb4962001-02-14 06:35:35 +0000386 return guts
Tim Peters8a7d2d52001-01-16 07:10:57 +0000387 def clear(self):
388 self.buf = []
Tim Petersc77db342001-10-23 02:21:52 +0000389 if hasattr(self, "softspace"):
390 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000391 def flush(self):
392 # JPython calls flush
393 pass
394
395# Display some tag-and-msg pairs nicely, keeping the tag and its msg
396# on the same line when that makes sense.
397
398def _tag_out(printer, *tag_msg_pairs):
399 for tag, msg in tag_msg_pairs:
400 printer(tag + ":")
401 msg_has_nl = msg[-1:] == "\n"
402 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000403 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000404 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
405 printer(" ")
406 else:
407 printer("\n")
408 printer(msg)
409 if not msg_has_nl:
410 printer("\n")
411
412# Run list of examples, in context globs. "out" can be used to display
413# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
414# that captures the examples' std output. Return (#failures, #tries).
415
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000416def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
417 compileflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000418 import sys, traceback
419 OK, BOOM, FAIL = range(3)
420 NADA = "nothing"
421 stderr = _SpoofOut()
422 failures = 0
423 for source, want, lineno in examples:
424 if verbose:
425 _tag_out(out, ("Trying", source),
426 ("Expecting", want or NADA))
427 fakeout.clear()
428 try:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000429 exec compile(source, "<string>", "single",
430 compileflags, 1) in globs
Tim Peters8a7d2d52001-01-16 07:10:57 +0000431 got = fakeout.get()
432 state = OK
433 except:
434 # See whether the exception was expected.
Tim Petersea4f9312001-02-13 20:54:42 +0000435 if want.find("Traceback (innermost last):\n") == 0 or \
436 want.find("Traceback (most recent call last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000437 # Only compare exception type and value - the rest of
438 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000439 want = want.split('\n')[-2] + '\n'
Tim Peters77f2d502001-06-24 18:59:01 +0000440 exc_type, exc_val = sys.exc_info()[:2]
Tim Peters08bba952001-06-24 06:46:58 +0000441 got = traceback.format_exception_only(exc_type, exc_val)[-1]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000442 state = OK
443 else:
444 # unexpected exception
445 stderr.clear()
446 traceback.print_exc(file=stderr)
447 state = BOOM
448
449 if state == OK:
450 if got == want:
451 if verbose:
452 out("ok\n")
453 continue
454 state = FAIL
455
456 assert state in (FAIL, BOOM)
457 failures = failures + 1
458 out("*" * 65 + "\n")
459 _tag_out(out, ("Failure in example", source))
460 out("from line #" + `lineno` + " of " + name + "\n")
461 if state == FAIL:
462 _tag_out(out, ("Expected", want or NADA), ("Got", got))
463 else:
464 assert state == BOOM
465 _tag_out(out, ("Exception raised", stderr.get()))
466
467 return failures, len(examples)
468
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000469# Get the future-flags associated with the future features that have been
470# imported into globs.
471
472def _extract_future_flags(globs):
473 flags = 0
474 for fname in __future__.all_feature_names:
475 feature = globs.get(fname, None)
476 if feature is getattr(__future__, fname):
477 flags |= feature.compiler_flag
478 return flags
479
Tim Petersd4ad59e2001-06-24 20:02:47 +0000480# Run list of examples, in a shallow copy of context (dict) globs.
481# Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000482
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000483def _run_examples(examples, globs, verbose, name, compileflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000484 import sys
485 saveout = sys.stdout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000486 globs = globs.copy()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000487 try:
488 sys.stdout = fakeout = _SpoofOut()
489 x = _run_examples_inner(saveout.write, fakeout, examples,
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000490 globs, verbose, name, compileflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000491 finally:
492 sys.stdout = saveout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000493 # While Python gc can clean up most cycles on its own, it doesn't
494 # chase frame objects. This is especially irksome when running
495 # generator tests that raise exceptions, because a named generator-
496 # iterator gets an entry in globs, and the generator-iterator
497 # object's frame's traceback info points back to globs. This is
Tim Petersfee69d02001-06-24 20:24:16 +0000498 # easy to break just by clearing the namespace. This can also
499 # help to break other kinds of cycles, and even for cycles that
500 # gc can break itself it's better to break them ASAP.
Tim Petersd4ad59e2001-06-24 20:02:47 +0000501 globs.clear()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000502 return x
503
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000504def run_docstring_examples(f, globs, verbose=0, name="NoName",
505 compileflags=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000506 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
507
Tim Petersd4ad59e2001-06-24 20:02:47 +0000508 Use (a shallow copy of) dict globs as the globals for execution.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000509 Return (#failures, #tries).
510
511 If optional arg verbose is true, print stuff even if there are no
512 failures.
513 Use string name in failure msgs.
514 """
515
516 try:
517 doc = f.__doc__
518 if not doc:
519 # docstring empty or None
520 return 0, 0
521 # just in case CT invents a doc object that has to be forced
522 # to look like a string <0.9 wink>
523 doc = str(doc)
524 except:
525 return 0, 0
526
527 e = _extract_examples(doc)
528 if not e:
529 return 0, 0
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000530 if compileflags is None:
531 compileflags = _extract_future_flags(globs)
532 return _run_examples(e, globs, verbose, name, compileflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000533
534def is_private(prefix, base):
535 """prefix, base -> true iff name prefix + "." + base is "private".
536
537 Prefix may be an empty string, and base does not contain a period.
538 Prefix is ignored (although functions you write conforming to this
539 protocol may make use of it).
540 Return true iff base begins with an (at least one) underscore, but
541 does not both begin and end with (at least) two underscores.
542
543 >>> is_private("a.b", "my_func")
544 0
545 >>> is_private("____", "_my_func")
546 1
547 >>> is_private("someclass", "__init__")
548 0
549 >>> is_private("sometypo", "__init_")
550 1
551 >>> is_private("x.y.z", "_")
552 1
553 >>> is_private("_x.y.z", "__")
554 0
555 >>> is_private("", "") # senseless but consistent
556 0
557 """
558
559 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
560
Tim Peters7402f792001-10-02 03:53:41 +0000561# Determine if a class of function was defined in the given module.
562
563def _from_module(module, object):
564 if _isfunction(object):
565 return module.__dict__ is object.func_globals
566 if _isclass(object):
567 return module.__name__ == object.__module__
568 raise ValueError("object must be a class or function")
569
Tim Peters8a7d2d52001-01-16 07:10:57 +0000570class Tester:
571 """Class Tester -- runs docstring examples and accumulates stats.
572
573In normal use, function doctest.testmod() hides all this from you,
574so use that if you can. Create your own instances of Tester to do
575fancier things.
576
577Methods:
578 runstring(s, name)
579 Search string s for examples to run; use name for logging.
580 Return (#failures, #tries).
581
582 rundoc(object, name=None)
583 Search object.__doc__ for examples to run; use name (or
584 object.__name__) for logging. Return (#failures, #tries).
585
Tim Peters7402f792001-10-02 03:53:41 +0000586 rundict(d, name, module=None)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000587 Search for examples in docstrings in all of d.values(); use name
Tim Peters7402f792001-10-02 03:53:41 +0000588 for logging. Exclude functions and classes not defined in module
589 if specified. Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000590
591 run__test__(d, name)
592 Treat dict d like module.__test__. Return (#failures, #tries).
593
594 summarize(verbose=None)
595 Display summary of testing results, to stdout. Return
596 (#failures, #tries).
597
598 merge(other)
599 Merge in the test results from Tester instance "other".
600
601>>> from doctest import Tester
602>>> t = Tester(globs={'x': 42}, verbose=0)
603>>> t.runstring(r'''
604... >>> x = x * 2
605... >>> print x
606... 42
607... ''', 'XYZ')
608*****************************************************************
609Failure in example: print x
610from line #2 of XYZ
611Expected: 42
612Got: 84
613(1, 2)
614>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
615(0, 2)
616>>> t.summarize()
Guido van Rossum261d91a2001-03-18 17:05:58 +0000617*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006181 items had failures:
619 1 of 2 in XYZ
620***Test Failed*** 1 failures.
621(1, 4)
622>>> t.summarize(verbose=1)
6231 items passed all tests:
624 2 tests in example2
Guido van Rossum261d91a2001-03-18 17:05:58 +0000625*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006261 items had failures:
627 1 of 2 in XYZ
6284 tests in 2 items.
6293 passed and 1 failed.
630***Test Failed*** 1 failures.
631(1, 4)
632>>>
633"""
634
635 def __init__(self, mod=None, globs=None, verbose=None,
636 isprivate=None):
637 """mod=None, globs=None, verbose=None, isprivate=None
638
639See doctest.__doc__ for an overview.
640
641Optional keyword arg "mod" is a module, whose globals are used for
642executing examples. If not specified, globs must be specified.
643
644Optional keyword arg "globs" gives a dict to be used as the globals
645when executing examples; if not specified, use the globals from
646module mod.
647
648In either case, a copy of the dict is used for each docstring
649examined.
650
651Optional keyword arg "verbose" prints lots of stuff if true, only
652failures if false; by default, it's true iff "-v" is in sys.argv.
653
654Optional keyword arg "isprivate" specifies a function used to determine
655whether a name is private. The default function is doctest.is_private;
656see its docs for details.
657"""
658
659 if mod is None and globs is None:
660 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters7402f792001-10-02 03:53:41 +0000661 if mod is not None and not _ismodule(mod):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000662 raise TypeError("Tester.__init__: mod must be a module; " +
663 `mod`)
664 if globs is None:
665 globs = mod.__dict__
666 self.globs = globs
667
668 if verbose is None:
669 import sys
670 verbose = "-v" in sys.argv
671 self.verbose = verbose
672
673 if isprivate is None:
674 isprivate = is_private
675 self.isprivate = isprivate
676
677 self.name2ft = {} # map name to (#failures, #trials) pair
678
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000679 self.compileflags = _extract_future_flags(globs)
680
Tim Peters8a7d2d52001-01-16 07:10:57 +0000681 def runstring(self, s, name):
682 """
683 s, name -> search string s for examples to run, logging as name.
684
685 Use string name as the key for logging the outcome.
686 Return (#failures, #examples).
687
688 >>> t = Tester(globs={}, verbose=1)
689 >>> test = r'''
690 ... # just an example
691 ... >>> x = 1 + 2
692 ... >>> x
693 ... 3
694 ... '''
695 >>> t.runstring(test, "Example")
696 Running string Example
697 Trying: x = 1 + 2
698 Expecting: nothing
699 ok
700 Trying: x
701 Expecting: 3
702 ok
703 0 of 2 examples failed in string Example
704 (0, 2)
705 """
706
707 if self.verbose:
708 print "Running string", name
709 f = t = 0
710 e = _extract_examples(s)
711 if e:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000712 f, t = _run_examples(e, self.globs, self.verbose, name,
713 self.compileflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000714 if self.verbose:
715 print f, "of", t, "examples failed in string", name
716 self.__record_outcome(name, f, t)
717 return f, t
718
719 def rundoc(self, object, name=None):
720 """
721 object, name=None -> search object.__doc__ for examples to run.
722
723 Use optional string name as the key for logging the outcome;
724 by default use object.__name__.
725 Return (#failures, #examples).
726 If object is a class object, search recursively for method
727 docstrings too.
728 object.__doc__ is examined regardless of name, but if object is
729 a class, whether private names reached from object are searched
730 depends on the constructor's "isprivate" argument.
731
732 >>> t = Tester(globs={}, verbose=0)
733 >>> def _f():
734 ... '''Trivial docstring example.
735 ... >>> assert 2 == 2
736 ... '''
737 ... return 32
738 ...
739 >>> t.rundoc(_f) # expect 0 failures in 1 example
740 (0, 1)
741 """
742
743 if name is None:
744 try:
745 name = object.__name__
746 except AttributeError:
747 raise ValueError("Tester.rundoc: name must be given "
748 "when object.__name__ doesn't exist; " + `object`)
749 if self.verbose:
750 print "Running", name + ".__doc__"
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000751 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
752 self.compileflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000753 if self.verbose:
754 print f, "of", t, "examples failed in", name + ".__doc__"
755 self.__record_outcome(name, f, t)
Tim Peters7402f792001-10-02 03:53:41 +0000756 if _isclass(object):
Tim Peters17111f32001-10-03 04:08:26 +0000757 # In 2.2, class and static methods complicate life. Build
758 # a dict "that works", by hook or by crook.
759 d = {}
760 for tag, kind, homecls, value in _classify_class_attrs(object):
761
762 if homecls is not object:
763 # Only look at names defined immediately by the class.
764 continue
765
766 elif self.isprivate(name, tag):
767 continue
768
769 elif kind == "method":
770 # value is already a function
771 d[tag] = value
772
773 elif kind == "static method":
774 # value isn't a function, but getattr reveals one
775 d[tag] = getattr(object, tag)
776
777 elif kind == "class method":
778 # Hmm. A classmethod object doesn't seem to reveal
779 # enough. But getattr turns it into a bound method,
780 # and from there .im_func retrieves the underlying
781 # function.
782 d[tag] = getattr(object, tag).im_func
783
784 elif kind == "property":
785 # The methods implementing the property have their
786 # own docstrings -- but the property may have one too.
787 if value.__doc__ is not None:
788 d[tag] = str(value.__doc__)
789
790 elif kind == "data":
791 # Grab nested classes.
792 if _isclass(value):
793 d[tag] = value
794
795 else:
796 raise ValueError("teach doctest about %r" % kind)
797
798 f2, t2 = self.run__test__(d, name)
799 f += f2
800 t += t2
801
Tim Peters8a7d2d52001-01-16 07:10:57 +0000802 return f, t
803
Tim Peters7402f792001-10-02 03:53:41 +0000804 def rundict(self, d, name, module=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000805 """
Tim Peters7402f792001-10-02 03:53:41 +0000806 d, name, module=None -> search for docstring examples in d.values().
Tim Peters8a7d2d52001-01-16 07:10:57 +0000807
808 For k, v in d.items() such that v is a function or class,
809 do self.rundoc(v, name + "." + k). Whether this includes
810 objects with private names depends on the constructor's
Tim Peters7402f792001-10-02 03:53:41 +0000811 "isprivate" argument. If module is specified, functions and
812 classes that are not defined in module are excluded.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000813 Return aggregate (#failures, #examples).
814
Tim Peters7402f792001-10-02 03:53:41 +0000815 Build and populate two modules with sample functions to test that
816 exclusion of external functions and classes works.
817
818 >>> import new
819 >>> m1 = new.module('_m1')
820 >>> m2 = new.module('_m2')
821 >>> test_data = \"""
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000822 ... def _f():
Tim Peters7402f792001-10-02 03:53:41 +0000823 ... '''>>> assert 1 == 1
824 ... '''
825 ... def g():
Tim Peters8a7d2d52001-01-16 07:10:57 +0000826 ... '''>>> assert 2 != 1
827 ... '''
Tim Peters7402f792001-10-02 03:53:41 +0000828 ... class H:
829 ... '''>>> assert 2 > 1
830 ... '''
831 ... def bar(self):
832 ... '''>>> assert 1 < 2
833 ... '''
834 ... \"""
835 >>> exec test_data in m1.__dict__
836 >>> exec test_data in m2.__dict__
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000837 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tim Peters7402f792001-10-02 03:53:41 +0000838
839 Tests that objects outside m1 are excluded:
840
Tim Peters8a7d2d52001-01-16 07:10:57 +0000841 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000842 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000843 (0, 3)
844
845 Again, but with a custom isprivate function allowing _f:
846
Tim Peters8a7d2d52001-01-16 07:10:57 +0000847 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000848 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000849 (0, 4)
850
851 And once more, not excluding stuff outside m1:
852
853 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000854 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Tim Peters7402f792001-10-02 03:53:41 +0000855 (0, 8)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000856
857 The exclusion of objects from outside the designated module is
858 meant to be invoked automagically by testmod.
859
860 >>> testmod(m1)
861 (0, 3)
862
Tim Peters8a7d2d52001-01-16 07:10:57 +0000863 """
864
865 if not hasattr(d, "items"):
866 raise TypeError("Tester.rundict: d must support .items(); " +
867 `d`)
868 f = t = 0
Tim Peters24a41912001-03-21 23:07:59 +0000869 # Run the tests by alpha order of names, for consistency in
870 # verbose-mode output.
871 names = d.keys()
872 names.sort()
873 for thisname in names:
874 value = d[thisname]
Tim Peters7402f792001-10-02 03:53:41 +0000875 if _isfunction(value) or _isclass(value):
876 if module and not _from_module(module, value):
877 continue
Tim Peters8a7d2d52001-01-16 07:10:57 +0000878 f2, t2 = self.__runone(value, name + "." + thisname)
879 f = f + f2
880 t = t + t2
881 return f, t
882
883 def run__test__(self, d, name):
884 """d, name -> Treat dict d like module.__test__.
885
886 Return (#failures, #tries).
887 See testmod.__doc__ for details.
888 """
889
890 failures = tries = 0
891 prefix = name + "."
892 savepvt = self.isprivate
893 try:
894 self.isprivate = lambda *args: 0
Tim Peters24a41912001-03-21 23:07:59 +0000895 # Run the tests by alpha order of names, for consistency in
896 # verbose-mode output.
897 keys = d.keys()
898 keys.sort()
899 for k in keys:
900 v = d[k]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000901 thisname = prefix + k
Tim Peters7402f792001-10-02 03:53:41 +0000902 if type(v) in _StringTypes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000903 f, t = self.runstring(v, thisname)
Tim Peters7402f792001-10-02 03:53:41 +0000904 elif _isfunction(v) or _isclass(v):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000905 f, t = self.rundoc(v, thisname)
906 else:
907 raise TypeError("Tester.run__test__: values in "
908 "dict must be strings, functions "
909 "or classes; " + `v`)
910 failures = failures + f
911 tries = tries + t
912 finally:
913 self.isprivate = savepvt
914 return failures, tries
915
916 def summarize(self, verbose=None):
917 """
918 verbose=None -> summarize results, return (#failures, #tests).
919
920 Print summary of test results to stdout.
921 Optional arg 'verbose' controls how wordy this is. By
922 default, use the verbose setting established by the
923 constructor.
924 """
925
926 if verbose is None:
927 verbose = self.verbose
928 notests = []
929 passed = []
930 failed = []
931 totalt = totalf = 0
932 for x in self.name2ft.items():
933 name, (f, t) = x
934 assert f <= t
935 totalt = totalt + t
936 totalf = totalf + f
937 if t == 0:
938 notests.append(name)
939 elif f == 0:
940 passed.append( (name, t) )
941 else:
942 failed.append(x)
943 if verbose:
944 if notests:
945 print len(notests), "items had no tests:"
946 notests.sort()
947 for thing in notests:
948 print " ", thing
949 if passed:
950 print len(passed), "items passed all tests:"
951 passed.sort()
952 for thing, count in passed:
953 print " %3d tests in %s" % (count, thing)
954 if failed:
Guido van Rossumaf00a462001-03-18 16:58:44 +0000955 print "*" * 65
Tim Peters8a7d2d52001-01-16 07:10:57 +0000956 print len(failed), "items had failures:"
957 failed.sort()
958 for thing, (f, t) in failed:
959 print " %3d of %3d in %s" % (f, t, thing)
960 if verbose:
961 print totalt, "tests in", len(self.name2ft), "items."
962 print totalt - totalf, "passed and", totalf, "failed."
963 if totalf:
964 print "***Test Failed***", totalf, "failures."
965 elif verbose:
966 print "Test passed."
967 return totalf, totalt
968
969 def merge(self, other):
970 """
971 other -> merge in test results from the other Tester instance.
972
973 If self and other both have a test result for something
974 with the same name, the (#failures, #tests) results are
975 summed, and a warning is printed to stdout.
976
977 >>> from doctest import Tester
978 >>> t1 = Tester(globs={}, verbose=0)
979 >>> t1.runstring('''
980 ... >>> x = 12
981 ... >>> print x
982 ... 12
983 ... ''', "t1example")
984 (0, 2)
985 >>>
986 >>> t2 = Tester(globs={}, verbose=0)
987 >>> t2.runstring('''
988 ... >>> x = 13
989 ... >>> print x
990 ... 13
991 ... ''', "t2example")
992 (0, 2)
993 >>> common = ">>> assert 1 + 2 == 3\\n"
994 >>> t1.runstring(common, "common")
995 (0, 1)
996 >>> t2.runstring(common, "common")
997 (0, 1)
998 >>> t1.merge(t2)
999 *** Tester.merge: 'common' in both testers; summing outcomes.
1000 >>> t1.summarize(1)
1001 3 items passed all tests:
1002 2 tests in common
1003 2 tests in t1example
1004 2 tests in t2example
1005 6 tests in 3 items.
1006 6 passed and 0 failed.
1007 Test passed.
1008 (0, 6)
1009 >>>
1010 """
1011
1012 d = self.name2ft
1013 for name, (f, t) in other.name2ft.items():
1014 if d.has_key(name):
1015 print "*** Tester.merge: '" + name + "' in both" \
1016 " testers; summing outcomes."
1017 f2, t2 = d[name]
1018 f = f + f2
1019 t = t + t2
1020 d[name] = f, t
1021
1022 def __record_outcome(self, name, f, t):
1023 if self.name2ft.has_key(name):
1024 print "*** Warning: '" + name + "' was tested before;", \
1025 "summing outcomes."
1026 f2, t2 = self.name2ft[name]
1027 f = f + f2
1028 t = t + t2
1029 self.name2ft[name] = f, t
1030
1031 def __runone(self, target, name):
1032 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +00001033 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001034 prefix, base = name[:i], name[i+1:]
1035 else:
1036 prefix, base = "", base
1037 if self.isprivate(prefix, base):
1038 return 0, 0
1039 return self.rundoc(target, name)
1040
1041master = None
1042
1043def testmod(m, name=None, globs=None, verbose=None, isprivate=None,
1044 report=1):
1045 """m, name=None, globs=None, verbose=None, isprivate=None, report=1
1046
1047 Test examples in docstrings in functions and classes reachable from
1048 module m, starting with m.__doc__. Private names are skipped.
1049
1050 Also test examples reachable from dict m.__test__ if it exists and is
1051 not None. m.__dict__ maps names to functions, classes and strings;
1052 function and class docstrings are tested even if the name is private;
1053 strings are tested directly, as if they were docstrings.
1054
1055 Return (#failures, #tests).
1056
1057 See doctest.__doc__ for an overview.
1058
1059 Optional keyword arg "name" gives the name of the module; by default
1060 use m.__name__.
1061
1062 Optional keyword arg "globs" gives a dict to be used as the globals
1063 when executing examples; by default, use m.__dict__. A copy of this
1064 dict is actually used for each docstring, so that each docstring's
1065 examples start with a clean slate.
1066
1067 Optional keyword arg "verbose" prints lots of stuff if true, prints
1068 only failures if false; by default, it's true iff "-v" is in sys.argv.
1069
1070 Optional keyword arg "isprivate" specifies a function used to
1071 determine whether a name is private. The default function is
1072 doctest.is_private; see its docs for details.
1073
1074 Optional keyword arg "report" prints a summary at the end when true,
1075 else prints nothing at the end. In verbose mode, the summary is
1076 detailed, else very brief (in fact, empty if all tests passed).
1077
1078 Advanced tomfoolery: testmod runs methods of a local instance of
1079 class doctest.Tester, then merges the results into (or creates)
1080 global Tester instance doctest.master. Methods of doctest.master
1081 can be called directly too, if you want to do something unusual.
1082 Passing report=0 to testmod is especially useful then, to delay
1083 displaying a summary. Invoke doctest.master.summarize(verbose)
1084 when you're done fiddling.
1085 """
1086
1087 global master
1088
Tim Peters7402f792001-10-02 03:53:41 +00001089 if not _ismodule(m):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001090 raise TypeError("testmod: module required; " + `m`)
1091 if name is None:
1092 name = m.__name__
1093 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate)
1094 failures, tries = tester.rundoc(m, name)
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001095 f, t = tester.rundict(m.__dict__, name, m)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001096 failures = failures + f
1097 tries = tries + t
1098 if hasattr(m, "__test__"):
1099 testdict = m.__test__
1100 if testdict:
1101 if not hasattr(testdict, "items"):
1102 raise TypeError("testmod: module.__test__ must support "
1103 ".items(); " + `testdict`)
1104 f, t = tester.run__test__(testdict, name + ".__test__")
1105 failures = failures + f
1106 tries = tries + t
1107 if report:
1108 tester.summarize()
1109 if master is None:
1110 master = tester
1111 else:
1112 master.merge(tester)
1113 return failures, tries
1114
1115class _TestClass:
1116 """
1117 A pointless class, for sanity-checking of docstring testing.
1118
1119 Methods:
1120 square()
1121 get()
1122
1123 >>> _TestClass(13).get() + _TestClass(-12).get()
1124 1
1125 >>> hex(_TestClass(13).square().get())
1126 '0xa9'
1127 """
1128
1129 def __init__(self, val):
1130 """val -> _TestClass object with associated value val.
1131
1132 >>> t = _TestClass(123)
1133 >>> print t.get()
1134 123
1135 """
1136
1137 self.val = val
1138
1139 def square(self):
1140 """square() -> square TestClass's associated value
1141
1142 >>> _TestClass(13).square().get()
1143 169
1144 """
1145
1146 self.val = self.val ** 2
1147 return self
1148
1149 def get(self):
1150 """get() -> return TestClass's associated value.
1151
1152 >>> x = _TestClass(-42)
1153 >>> print x.get()
1154 -42
1155 """
1156
1157 return self.val
1158
1159__test__ = {"_TestClass": _TestClass,
1160 "string": r"""
1161 Example of a string object, searched as-is.
1162 >>> x = 1; y = 2
1163 >>> x + y, x * y
1164 (3, 2)
1165 """
1166 }
1167
1168def _test():
1169 import doctest
1170 return doctest.testmod(doctest)
1171
1172if __name__ == "__main__":
1173 _test()