blob: 4689efed1b67c9f129b40ca860af92edabe72c57 [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
261 7 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
27053 tests in 17 items.
27153 passed and 0 failed.
272Test 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
298
Tim Peters8a7d2d52001-01-16 07:10:57 +0000299# Extract interactive examples from a string. Return a list of triples,
300# (source, outcome, lineno). "source" is the source code, and ends
301# with a newline iff the source spans more than one line. "outcome" is
302# the expected output if any, else an empty string. When not empty,
303# outcome always ends with a newline. "lineno" is the line number,
304# 0-based wrt the start of the string, of the first source line.
305
306def _extract_examples(s):
307 isPS1, isPS2 = _isPS1, _isPS2
308 isEmpty, isComment = _isEmpty, _isComment
309 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000310 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000311 i, n = 0, len(lines)
312 while i < n:
313 line = lines[i]
314 i = i + 1
315 m = isPS1(line)
316 if m is None:
317 continue
318 j = m.end(0) # beyond the prompt
319 if isEmpty(line, j) or isComment(line, j):
320 # a bare prompt or comment -- not interesting
321 continue
322 lineno = i - 1
323 if line[j] != " ":
324 raise ValueError("line " + `lineno` + " of docstring lacks "
325 "blank after " + PS1 + ": " + line)
326 j = j + 1
327 blanks = m.group(1)
328 nblanks = len(blanks)
329 # suck up this and following PS2 lines
330 source = []
331 while 1:
332 source.append(line[j:])
333 line = lines[i]
334 m = isPS2(line)
335 if m:
336 if m.group(1) != blanks:
337 raise ValueError("inconsistent leading whitespace "
338 "in line " + `i` + " of docstring: " + line)
339 i = i + 1
340 else:
341 break
342 if len(source) == 1:
343 source = source[0]
344 else:
345 # get rid of useless null line from trailing empty "..."
346 if source[-1] == "":
347 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000348 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000349 # suck up response
350 if isPS1(line) or isEmpty(line):
351 expect = ""
352 else:
353 expect = []
354 while 1:
355 if line[:nblanks] != blanks:
356 raise ValueError("inconsistent leading whitespace "
357 "in line " + `i` + " of docstring: " + line)
358 expect.append(line[nblanks:])
359 i = i + 1
360 line = lines[i]
361 if isPS1(line) or isEmpty(line):
362 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000363 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000364 examples.append( (source, expect, lineno) )
365 return examples
366
367# Capture stdout when running examples.
368
369class _SpoofOut:
370 def __init__(self):
371 self.clear()
372 def write(self, s):
373 self.buf.append(s)
374 def get(self):
Tim Petersf9bb4962001-02-14 06:35:35 +0000375 guts = "".join(self.buf)
376 # If anything at all was written, make sure there's a trailing
377 # newline. There's no way for the expected output to indicate
378 # that a trailing newline is missing.
379 if guts and not guts.endswith("\n"):
380 guts = guts + "\n"
381 return guts
Tim Peters8a7d2d52001-01-16 07:10:57 +0000382 def clear(self):
383 self.buf = []
384 def flush(self):
385 # JPython calls flush
386 pass
387
388# Display some tag-and-msg pairs nicely, keeping the tag and its msg
389# on the same line when that makes sense.
390
391def _tag_out(printer, *tag_msg_pairs):
392 for tag, msg in tag_msg_pairs:
393 printer(tag + ":")
394 msg_has_nl = msg[-1:] == "\n"
395 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000396 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000397 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
398 printer(" ")
399 else:
400 printer("\n")
401 printer(msg)
402 if not msg_has_nl:
403 printer("\n")
404
405# Run list of examples, in context globs. "out" can be used to display
406# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
407# that captures the examples' std output. Return (#failures, #tries).
408
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000409def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
410 compileflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000411 import sys, traceback
412 OK, BOOM, FAIL = range(3)
413 NADA = "nothing"
414 stderr = _SpoofOut()
415 failures = 0
416 for source, want, lineno in examples:
417 if verbose:
418 _tag_out(out, ("Trying", source),
419 ("Expecting", want or NADA))
420 fakeout.clear()
421 try:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000422 exec compile(source, "<string>", "single",
423 compileflags, 1) in globs
Tim Peters8a7d2d52001-01-16 07:10:57 +0000424 got = fakeout.get()
425 state = OK
426 except:
427 # See whether the exception was expected.
Tim Petersea4f9312001-02-13 20:54:42 +0000428 if want.find("Traceback (innermost last):\n") == 0 or \
429 want.find("Traceback (most recent call last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000430 # Only compare exception type and value - the rest of
431 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000432 want = want.split('\n')[-2] + '\n'
Tim Peters77f2d502001-06-24 18:59:01 +0000433 exc_type, exc_val = sys.exc_info()[:2]
Tim Peters08bba952001-06-24 06:46:58 +0000434 got = traceback.format_exception_only(exc_type, exc_val)[-1]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000435 state = OK
436 else:
437 # unexpected exception
438 stderr.clear()
439 traceback.print_exc(file=stderr)
440 state = BOOM
441
442 if state == OK:
443 if got == want:
444 if verbose:
445 out("ok\n")
446 continue
447 state = FAIL
448
449 assert state in (FAIL, BOOM)
450 failures = failures + 1
451 out("*" * 65 + "\n")
452 _tag_out(out, ("Failure in example", source))
453 out("from line #" + `lineno` + " of " + name + "\n")
454 if state == FAIL:
455 _tag_out(out, ("Expected", want or NADA), ("Got", got))
456 else:
457 assert state == BOOM
458 _tag_out(out, ("Exception raised", stderr.get()))
459
460 return failures, len(examples)
461
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000462# Get the future-flags associated with the future features that have been
463# imported into globs.
464
465def _extract_future_flags(globs):
466 flags = 0
467 for fname in __future__.all_feature_names:
468 feature = globs.get(fname, None)
469 if feature is getattr(__future__, fname):
470 flags |= feature.compiler_flag
471 return flags
472
Tim Petersd4ad59e2001-06-24 20:02:47 +0000473# Run list of examples, in a shallow copy of context (dict) globs.
474# Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000475
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000476def _run_examples(examples, globs, verbose, name, compileflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000477 import sys
478 saveout = sys.stdout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000479 globs = globs.copy()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000480 try:
481 sys.stdout = fakeout = _SpoofOut()
482 x = _run_examples_inner(saveout.write, fakeout, examples,
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000483 globs, verbose, name, compileflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000484 finally:
485 sys.stdout = saveout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000486 # While Python gc can clean up most cycles on its own, it doesn't
487 # chase frame objects. This is especially irksome when running
488 # generator tests that raise exceptions, because a named generator-
489 # iterator gets an entry in globs, and the generator-iterator
490 # object's frame's traceback info points back to globs. This is
Tim Petersfee69d02001-06-24 20:24:16 +0000491 # easy to break just by clearing the namespace. This can also
492 # help to break other kinds of cycles, and even for cycles that
493 # gc can break itself it's better to break them ASAP.
Tim Petersd4ad59e2001-06-24 20:02:47 +0000494 globs.clear()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000495 return x
496
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000497def run_docstring_examples(f, globs, verbose=0, name="NoName",
498 compileflags=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000499 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
500
Tim Petersd4ad59e2001-06-24 20:02:47 +0000501 Use (a shallow copy of) dict globs as the globals for execution.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000502 Return (#failures, #tries).
503
504 If optional arg verbose is true, print stuff even if there are no
505 failures.
506 Use string name in failure msgs.
507 """
508
509 try:
510 doc = f.__doc__
511 if not doc:
512 # docstring empty or None
513 return 0, 0
514 # just in case CT invents a doc object that has to be forced
515 # to look like a string <0.9 wink>
516 doc = str(doc)
517 except:
518 return 0, 0
519
520 e = _extract_examples(doc)
521 if not e:
522 return 0, 0
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000523 if compileflags is None:
524 compileflags = _extract_future_flags(globs)
525 return _run_examples(e, globs, verbose, name, compileflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000526
527def is_private(prefix, base):
528 """prefix, base -> true iff name prefix + "." + base is "private".
529
530 Prefix may be an empty string, and base does not contain a period.
531 Prefix is ignored (although functions you write conforming to this
532 protocol may make use of it).
533 Return true iff base begins with an (at least one) underscore, but
534 does not both begin and end with (at least) two underscores.
535
536 >>> is_private("a.b", "my_func")
537 0
538 >>> is_private("____", "_my_func")
539 1
540 >>> is_private("someclass", "__init__")
541 0
542 >>> is_private("sometypo", "__init_")
543 1
544 >>> is_private("x.y.z", "_")
545 1
546 >>> is_private("_x.y.z", "__")
547 0
548 >>> is_private("", "") # senseless but consistent
549 0
550 """
551
552 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
553
Tim Peters7402f792001-10-02 03:53:41 +0000554# Determine if a class of function was defined in the given module.
555
556def _from_module(module, object):
557 if _isfunction(object):
558 return module.__dict__ is object.func_globals
559 if _isclass(object):
560 return module.__name__ == object.__module__
561 raise ValueError("object must be a class or function")
562
Tim Peters8a7d2d52001-01-16 07:10:57 +0000563class Tester:
564 """Class Tester -- runs docstring examples and accumulates stats.
565
566In normal use, function doctest.testmod() hides all this from you,
567so use that if you can. Create your own instances of Tester to do
568fancier things.
569
570Methods:
571 runstring(s, name)
572 Search string s for examples to run; use name for logging.
573 Return (#failures, #tries).
574
575 rundoc(object, name=None)
576 Search object.__doc__ for examples to run; use name (or
577 object.__name__) for logging. Return (#failures, #tries).
578
Tim Peters7402f792001-10-02 03:53:41 +0000579 rundict(d, name, module=None)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000580 Search for examples in docstrings in all of d.values(); use name
Tim Peters7402f792001-10-02 03:53:41 +0000581 for logging. Exclude functions and classes not defined in module
582 if specified. Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000583
584 run__test__(d, name)
585 Treat dict d like module.__test__. Return (#failures, #tries).
586
587 summarize(verbose=None)
588 Display summary of testing results, to stdout. Return
589 (#failures, #tries).
590
591 merge(other)
592 Merge in the test results from Tester instance "other".
593
594>>> from doctest import Tester
595>>> t = Tester(globs={'x': 42}, verbose=0)
596>>> t.runstring(r'''
597... >>> x = x * 2
598... >>> print x
599... 42
600... ''', 'XYZ')
601*****************************************************************
602Failure in example: print x
603from line #2 of XYZ
604Expected: 42
605Got: 84
606(1, 2)
607>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
608(0, 2)
609>>> t.summarize()
Guido van Rossum261d91a2001-03-18 17:05:58 +0000610*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006111 items had failures:
612 1 of 2 in XYZ
613***Test Failed*** 1 failures.
614(1, 4)
615>>> t.summarize(verbose=1)
6161 items passed all tests:
617 2 tests in example2
Guido van Rossum261d91a2001-03-18 17:05:58 +0000618*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006191 items had failures:
620 1 of 2 in XYZ
6214 tests in 2 items.
6223 passed and 1 failed.
623***Test Failed*** 1 failures.
624(1, 4)
625>>>
626"""
627
628 def __init__(self, mod=None, globs=None, verbose=None,
629 isprivate=None):
630 """mod=None, globs=None, verbose=None, isprivate=None
631
632See doctest.__doc__ for an overview.
633
634Optional keyword arg "mod" is a module, whose globals are used for
635executing examples. If not specified, globs must be specified.
636
637Optional keyword arg "globs" gives a dict to be used as the globals
638when executing examples; if not specified, use the globals from
639module mod.
640
641In either case, a copy of the dict is used for each docstring
642examined.
643
644Optional keyword arg "verbose" prints lots of stuff if true, only
645failures if false; by default, it's true iff "-v" is in sys.argv.
646
647Optional keyword arg "isprivate" specifies a function used to determine
648whether a name is private. The default function is doctest.is_private;
649see its docs for details.
650"""
651
652 if mod is None and globs is None:
653 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters7402f792001-10-02 03:53:41 +0000654 if mod is not None and not _ismodule(mod):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000655 raise TypeError("Tester.__init__: mod must be a module; " +
656 `mod`)
657 if globs is None:
658 globs = mod.__dict__
659 self.globs = globs
660
661 if verbose is None:
662 import sys
663 verbose = "-v" in sys.argv
664 self.verbose = verbose
665
666 if isprivate is None:
667 isprivate = is_private
668 self.isprivate = isprivate
669
670 self.name2ft = {} # map name to (#failures, #trials) pair
671
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000672 self.compileflags = _extract_future_flags(globs)
673
Tim Peters8a7d2d52001-01-16 07:10:57 +0000674 def runstring(self, s, name):
675 """
676 s, name -> search string s for examples to run, logging as name.
677
678 Use string name as the key for logging the outcome.
679 Return (#failures, #examples).
680
681 >>> t = Tester(globs={}, verbose=1)
682 >>> test = r'''
683 ... # just an example
684 ... >>> x = 1 + 2
685 ... >>> x
686 ... 3
687 ... '''
688 >>> t.runstring(test, "Example")
689 Running string Example
690 Trying: x = 1 + 2
691 Expecting: nothing
692 ok
693 Trying: x
694 Expecting: 3
695 ok
696 0 of 2 examples failed in string Example
697 (0, 2)
698 """
699
700 if self.verbose:
701 print "Running string", name
702 f = t = 0
703 e = _extract_examples(s)
704 if e:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000705 f, t = _run_examples(e, self.globs, self.verbose, name,
706 self.compileflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000707 if self.verbose:
708 print f, "of", t, "examples failed in string", name
709 self.__record_outcome(name, f, t)
710 return f, t
711
712 def rundoc(self, object, name=None):
713 """
714 object, name=None -> search object.__doc__ for examples to run.
715
716 Use optional string name as the key for logging the outcome;
717 by default use object.__name__.
718 Return (#failures, #examples).
719 If object is a class object, search recursively for method
720 docstrings too.
721 object.__doc__ is examined regardless of name, but if object is
722 a class, whether private names reached from object are searched
723 depends on the constructor's "isprivate" argument.
724
725 >>> t = Tester(globs={}, verbose=0)
726 >>> def _f():
727 ... '''Trivial docstring example.
728 ... >>> assert 2 == 2
729 ... '''
730 ... return 32
731 ...
732 >>> t.rundoc(_f) # expect 0 failures in 1 example
733 (0, 1)
734 """
735
736 if name is None:
737 try:
738 name = object.__name__
739 except AttributeError:
740 raise ValueError("Tester.rundoc: name must be given "
741 "when object.__name__ doesn't exist; " + `object`)
742 if self.verbose:
743 print "Running", name + ".__doc__"
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000744 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
745 self.compileflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000746 if self.verbose:
747 print f, "of", t, "examples failed in", name + ".__doc__"
748 self.__record_outcome(name, f, t)
Tim Peters7402f792001-10-02 03:53:41 +0000749 if _isclass(object):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000750 f2, t2 = self.rundict(object.__dict__, name)
751 f = f + f2
752 t = t + t2
753 return f, t
754
Tim Peters7402f792001-10-02 03:53:41 +0000755 def rundict(self, d, name, module=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000756 """
Tim Peters7402f792001-10-02 03:53:41 +0000757 d, name, module=None -> search for docstring examples in d.values().
Tim Peters8a7d2d52001-01-16 07:10:57 +0000758
759 For k, v in d.items() such that v is a function or class,
760 do self.rundoc(v, name + "." + k). Whether this includes
761 objects with private names depends on the constructor's
Tim Peters7402f792001-10-02 03:53:41 +0000762 "isprivate" argument. If module is specified, functions and
763 classes that are not defined in module are excluded.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000764 Return aggregate (#failures, #examples).
765
Tim Peters7402f792001-10-02 03:53:41 +0000766 Build and populate two modules with sample functions to test that
767 exclusion of external functions and classes works.
768
769 >>> import new
770 >>> m1 = new.module('_m1')
771 >>> m2 = new.module('_m2')
772 >>> test_data = \"""
773 ... def f():
774 ... '''>>> assert 1 == 1
775 ... '''
776 ... def g():
Tim Peters8a7d2d52001-01-16 07:10:57 +0000777 ... '''>>> assert 2 != 1
778 ... '''
Tim Peters7402f792001-10-02 03:53:41 +0000779 ... class H:
780 ... '''>>> assert 2 > 1
781 ... '''
782 ... def bar(self):
783 ... '''>>> assert 1 < 2
784 ... '''
785 ... \"""
786 >>> exec test_data in m1.__dict__
787 >>> exec test_data in m2.__dict__
788
789 Tests that objects outside m1 are excluded:
790
791 >>> d = {"_f": m1.f, "g": m1.g, "h": m1.H,
792 ... "f2": m2.f, "g2": m2.g, "h2": m2.H}
Tim Peters8a7d2d52001-01-16 07:10:57 +0000793 >>> t = Tester(globs={}, verbose=0)
Tim Peters7402f792001-10-02 03:53:41 +0000794 >>> t.rundict(d, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
795 (0, 3)
796
797 Again, but with a custom isprivate function allowing _f:
798
Tim Peters8a7d2d52001-01-16 07:10:57 +0000799 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
Tim Peters7402f792001-10-02 03:53:41 +0000800 >>> t.rundict(d, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
801 (0, 4)
802
803 And once more, not excluding stuff outside m1:
804
805 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
806 >>> t.rundict(d, "rundict_test_pvt") # None are skipped.
807 (0, 8)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000808 """
809
810 if not hasattr(d, "items"):
811 raise TypeError("Tester.rundict: d must support .items(); " +
812 `d`)
813 f = t = 0
Tim Peters24a41912001-03-21 23:07:59 +0000814 # Run the tests by alpha order of names, for consistency in
815 # verbose-mode output.
816 names = d.keys()
817 names.sort()
818 for thisname in names:
819 value = d[thisname]
Tim Peters7402f792001-10-02 03:53:41 +0000820 if _isfunction(value) or _isclass(value):
821 if module and not _from_module(module, value):
822 continue
Tim Peters8a7d2d52001-01-16 07:10:57 +0000823 f2, t2 = self.__runone(value, name + "." + thisname)
824 f = f + f2
825 t = t + t2
826 return f, t
827
828 def run__test__(self, d, name):
829 """d, name -> Treat dict d like module.__test__.
830
831 Return (#failures, #tries).
832 See testmod.__doc__ for details.
833 """
834
835 failures = tries = 0
836 prefix = name + "."
837 savepvt = self.isprivate
838 try:
839 self.isprivate = lambda *args: 0
Tim Peters24a41912001-03-21 23:07:59 +0000840 # Run the tests by alpha order of names, for consistency in
841 # verbose-mode output.
842 keys = d.keys()
843 keys.sort()
844 for k in keys:
845 v = d[k]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000846 thisname = prefix + k
Tim Peters7402f792001-10-02 03:53:41 +0000847 if type(v) in _StringTypes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000848 f, t = self.runstring(v, thisname)
Tim Peters7402f792001-10-02 03:53:41 +0000849 elif _isfunction(v) or _isclass(v):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000850 f, t = self.rundoc(v, thisname)
851 else:
852 raise TypeError("Tester.run__test__: values in "
853 "dict must be strings, functions "
854 "or classes; " + `v`)
855 failures = failures + f
856 tries = tries + t
857 finally:
858 self.isprivate = savepvt
859 return failures, tries
860
861 def summarize(self, verbose=None):
862 """
863 verbose=None -> summarize results, return (#failures, #tests).
864
865 Print summary of test results to stdout.
866 Optional arg 'verbose' controls how wordy this is. By
867 default, use the verbose setting established by the
868 constructor.
869 """
870
871 if verbose is None:
872 verbose = self.verbose
873 notests = []
874 passed = []
875 failed = []
876 totalt = totalf = 0
877 for x in self.name2ft.items():
878 name, (f, t) = x
879 assert f <= t
880 totalt = totalt + t
881 totalf = totalf + f
882 if t == 0:
883 notests.append(name)
884 elif f == 0:
885 passed.append( (name, t) )
886 else:
887 failed.append(x)
888 if verbose:
889 if notests:
890 print len(notests), "items had no tests:"
891 notests.sort()
892 for thing in notests:
893 print " ", thing
894 if passed:
895 print len(passed), "items passed all tests:"
896 passed.sort()
897 for thing, count in passed:
898 print " %3d tests in %s" % (count, thing)
899 if failed:
Guido van Rossumaf00a462001-03-18 16:58:44 +0000900 print "*" * 65
Tim Peters8a7d2d52001-01-16 07:10:57 +0000901 print len(failed), "items had failures:"
902 failed.sort()
903 for thing, (f, t) in failed:
904 print " %3d of %3d in %s" % (f, t, thing)
905 if verbose:
906 print totalt, "tests in", len(self.name2ft), "items."
907 print totalt - totalf, "passed and", totalf, "failed."
908 if totalf:
909 print "***Test Failed***", totalf, "failures."
910 elif verbose:
911 print "Test passed."
912 return totalf, totalt
913
914 def merge(self, other):
915 """
916 other -> merge in test results from the other Tester instance.
917
918 If self and other both have a test result for something
919 with the same name, the (#failures, #tests) results are
920 summed, and a warning is printed to stdout.
921
922 >>> from doctest import Tester
923 >>> t1 = Tester(globs={}, verbose=0)
924 >>> t1.runstring('''
925 ... >>> x = 12
926 ... >>> print x
927 ... 12
928 ... ''', "t1example")
929 (0, 2)
930 >>>
931 >>> t2 = Tester(globs={}, verbose=0)
932 >>> t2.runstring('''
933 ... >>> x = 13
934 ... >>> print x
935 ... 13
936 ... ''', "t2example")
937 (0, 2)
938 >>> common = ">>> assert 1 + 2 == 3\\n"
939 >>> t1.runstring(common, "common")
940 (0, 1)
941 >>> t2.runstring(common, "common")
942 (0, 1)
943 >>> t1.merge(t2)
944 *** Tester.merge: 'common' in both testers; summing outcomes.
945 >>> t1.summarize(1)
946 3 items passed all tests:
947 2 tests in common
948 2 tests in t1example
949 2 tests in t2example
950 6 tests in 3 items.
951 6 passed and 0 failed.
952 Test passed.
953 (0, 6)
954 >>>
955 """
956
957 d = self.name2ft
958 for name, (f, t) in other.name2ft.items():
959 if d.has_key(name):
960 print "*** Tester.merge: '" + name + "' in both" \
961 " testers; summing outcomes."
962 f2, t2 = d[name]
963 f = f + f2
964 t = t + t2
965 d[name] = f, t
966
967 def __record_outcome(self, name, f, t):
968 if self.name2ft.has_key(name):
969 print "*** Warning: '" + name + "' was tested before;", \
970 "summing outcomes."
971 f2, t2 = self.name2ft[name]
972 f = f + f2
973 t = t + t2
974 self.name2ft[name] = f, t
975
976 def __runone(self, target, name):
977 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000978 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000979 prefix, base = name[:i], name[i+1:]
980 else:
981 prefix, base = "", base
982 if self.isprivate(prefix, base):
983 return 0, 0
984 return self.rundoc(target, name)
985
986master = None
987
988def testmod(m, name=None, globs=None, verbose=None, isprivate=None,
989 report=1):
990 """m, name=None, globs=None, verbose=None, isprivate=None, report=1
991
992 Test examples in docstrings in functions and classes reachable from
993 module m, starting with m.__doc__. Private names are skipped.
994
995 Also test examples reachable from dict m.__test__ if it exists and is
996 not None. m.__dict__ maps names to functions, classes and strings;
997 function and class docstrings are tested even if the name is private;
998 strings are tested directly, as if they were docstrings.
999
1000 Return (#failures, #tests).
1001
1002 See doctest.__doc__ for an overview.
1003
1004 Optional keyword arg "name" gives the name of the module; by default
1005 use m.__name__.
1006
1007 Optional keyword arg "globs" gives a dict to be used as the globals
1008 when executing examples; by default, use m.__dict__. A copy of this
1009 dict is actually used for each docstring, so that each docstring's
1010 examples start with a clean slate.
1011
1012 Optional keyword arg "verbose" prints lots of stuff if true, prints
1013 only failures if false; by default, it's true iff "-v" is in sys.argv.
1014
1015 Optional keyword arg "isprivate" specifies a function used to
1016 determine whether a name is private. The default function is
1017 doctest.is_private; see its docs for details.
1018
1019 Optional keyword arg "report" prints a summary at the end when true,
1020 else prints nothing at the end. In verbose mode, the summary is
1021 detailed, else very brief (in fact, empty if all tests passed).
1022
1023 Advanced tomfoolery: testmod runs methods of a local instance of
1024 class doctest.Tester, then merges the results into (or creates)
1025 global Tester instance doctest.master. Methods of doctest.master
1026 can be called directly too, if you want to do something unusual.
1027 Passing report=0 to testmod is especially useful then, to delay
1028 displaying a summary. Invoke doctest.master.summarize(verbose)
1029 when you're done fiddling.
1030 """
1031
1032 global master
1033
Tim Peters7402f792001-10-02 03:53:41 +00001034 if not _ismodule(m):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001035 raise TypeError("testmod: module required; " + `m`)
1036 if name is None:
1037 name = m.__name__
1038 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate)
1039 failures, tries = tester.rundoc(m, name)
1040 f, t = tester.rundict(m.__dict__, name)
1041 failures = failures + f
1042 tries = tries + t
1043 if hasattr(m, "__test__"):
1044 testdict = m.__test__
1045 if testdict:
1046 if not hasattr(testdict, "items"):
1047 raise TypeError("testmod: module.__test__ must support "
1048 ".items(); " + `testdict`)
1049 f, t = tester.run__test__(testdict, name + ".__test__")
1050 failures = failures + f
1051 tries = tries + t
1052 if report:
1053 tester.summarize()
1054 if master is None:
1055 master = tester
1056 else:
1057 master.merge(tester)
1058 return failures, tries
1059
1060class _TestClass:
1061 """
1062 A pointless class, for sanity-checking of docstring testing.
1063
1064 Methods:
1065 square()
1066 get()
1067
1068 >>> _TestClass(13).get() + _TestClass(-12).get()
1069 1
1070 >>> hex(_TestClass(13).square().get())
1071 '0xa9'
1072 """
1073
1074 def __init__(self, val):
1075 """val -> _TestClass object with associated value val.
1076
1077 >>> t = _TestClass(123)
1078 >>> print t.get()
1079 123
1080 """
1081
1082 self.val = val
1083
1084 def square(self):
1085 """square() -> square TestClass's associated value
1086
1087 >>> _TestClass(13).square().get()
1088 169
1089 """
1090
1091 self.val = self.val ** 2
1092 return self
1093
1094 def get(self):
1095 """get() -> return TestClass's associated value.
1096
1097 >>> x = _TestClass(-42)
1098 >>> print x.get()
1099 -42
1100 """
1101
1102 return self.val
1103
1104__test__ = {"_TestClass": _TestClass,
1105 "string": r"""
1106 Example of a string object, searched as-is.
1107 >>> x = 1; y = 2
1108 >>> x + y, x * y
1109 (3, 2)
1110 """
1111 }
1112
1113def _test():
1114 import doctest
1115 return doctest.testmod(doctest)
1116
1117if __name__ == "__main__":
1118 _test()