blob: acde9c13b4a5335ab46b3e6dc490d6eca67168a1 [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
Martin v. Löwis92816de2004-05-31 19:01:00 +00007r"""Module doctest -- a framework for running examples in docstrings.
Tim Peters8a7d2d52001-01-16 07:10:57 +00008
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
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000051 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000052
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000053+ C.__doc__ for all classes C in M.__dict__.values(), except those
54 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
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000065their contained methods and nested classes. All names reached from
66M.__test__ are searched.
Tim Peters8a7d2d52001-01-16 07:10:57 +000067
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000068Optionally, functions with private names can be skipped (unless listed in
69M.__test__) by supplying a function to the "isprivate" argument that will
70identify private functions. For convenience, one such function is
71supplied. docttest.is_private considers a name to be private if it begins
72with an underscore (like "_my_func") but doesn't both begin and end with
73(at least) two underscores (like "__init__"). By supplying this function
74or your own "isprivate" function to testmod, the behavior can be customized.
Tim Peters8a7d2d52001-01-16 07:10:57 +000075
76If you want to test docstrings in objects with private names too, stuff
77them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
78own isprivate function to Tester's constructor, or call the rundoc method
79of a Tester instance).
80
Tim Peters8a7d2d52001-01-16 07:10:57 +000081WHAT'S THE EXECUTION CONTEXT?
82
83By default, each time testmod finds a docstring to test, it uses a *copy*
84of M's globals (so that running tests on a module doesn't change the
85module's real globals, and so that one test in M can't leave behind crumbs
86that accidentally allow another test to work). This means examples can
87freely use any names defined at top-level in M. It also means that sloppy
88imports (see above) can cause examples in external docstrings to use
89globals inappropriate for them.
90
91You can force use of your own dict as the execution context by passing
92"globs=your_dict" to testmod instead. Presumably this would be a copy of
93M.__dict__ merged with the globals from other imported modules.
94
95
96WHAT IF I WANT TO TEST A WHOLE PACKAGE?
97
98Piece o' cake, provided the modules do their testing from docstrings.
99Here's the test.py I use for the world's most elaborate Rational/
100floating-base-conversion pkg (which I'll distribute some day):
101
102from Rational import Cvt
103from Rational import Format
104from Rational import machprec
105from Rational import Rat
106from Rational import Round
107from Rational import utils
108
109modules = (Cvt,
110 Format,
111 machprec,
112 Rat,
113 Round,
114 utils)
115
116def _test():
117 import doctest
118 import sys
119 verbose = "-v" in sys.argv
120 for mod in modules:
121 doctest.testmod(mod, verbose=verbose, report=0)
122 doctest.master.summarize()
123
124if __name__ == "__main__":
125 _test()
126
127IOW, it just runs testmod on all the pkg modules. testmod remembers the
128names and outcomes (# of failures, # of tries) for each item it's seen, and
129passing "report=0" prevents it from printing a summary in verbose mode.
130Instead, the summary is delayed until all modules have been tested, and
131then "doctest.master.summarize()" forces the summary at the end.
132
133So this is very nice in practice: each module can be tested individually
134with almost no work beyond writing up docstring examples, and collections
135of modules can be tested too as a unit with no more work than the above.
136
137
138WHAT ABOUT EXCEPTIONS?
139
140No problem, as long as the only output generated by the example is the
141traceback itself. For example:
142
Tim Peters60e23f42001-02-14 00:43:21 +0000143 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +0000144 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000145 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000146 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000147 >>>
148
149Note that only the exception type and value are compared (specifically,
150only the last line in the traceback).
151
152
153ADVANCED USAGE
154
155doctest.testmod() captures the testing policy I find most useful most
156often. You may want other policies.
157
158testmod() actually creates a local instance of class doctest.Tester, runs
159appropriate methods of that class, and merges the results into global
160Tester instance doctest.master.
161
162You can create your own instances of doctest.Tester, and so build your own
163policies, or even run methods of doctest.master directly. See
164doctest.Tester.__doc__ for details.
165
166
167SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
168
169Oh ya. It's easy! In most cases a copy-and-paste of an interactive
170console session works fine -- just make sure the leading whitespace is
171rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
172right, but doctest is not in the business of guessing what you think a tab
173means).
174
175 >>> # comments are ignored
176 >>> x = 12
177 >>> x
178 12
179 >>> if x == 13:
180 ... print "yes"
181 ... else:
182 ... print "no"
183 ... print "NO"
184 ... print "NO!!!"
185 ...
186 no
187 NO
188 NO!!!
189 >>>
190
191Any expected output must immediately follow the final ">>>" or "..." line
192containing the code, and the expected output (if any) extends to the next
193">>>" or all-whitespace line. That's it.
194
195Bummers:
196
197+ Expected output cannot contain an all-whitespace line, since such a line
198 is taken to signal the end of expected output.
199
200+ Output to stdout is captured, but not output to stderr (exception
201 tracebacks are captured via a different means).
202
Martin v. Löwis92816de2004-05-31 19:01:00 +0000203+ If you continue a line via backslashing in an interactive session,
204 or for any other reason use a backslash, you should use a raw
205 docstring, which will preserve your backslahses exactly as you type
206 them:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000207
Martin v. Löwis92816de2004-05-31 19:01:00 +0000208 >>> def f(x):
209 ... r'''Backslashes in a raw docstring: m\n'''
210 >>> print f.__doc__
211 Backslashes in a raw docstring: m\n
Tim Peters8a7d2d52001-01-16 07:10:57 +0000212
Martin v. Löwis92816de2004-05-31 19:01:00 +0000213 Otherwise, the backslash will be interpreted as part of the string.
214 E.g., the "\n" above would be interpreted as a newline character.
215 Alternatively, you can double each backslash in the doctest version
216 (and not use a raw string):
217
218 >>> def f(x):
219 ... '''Backslashes in a raw docstring: m\\n'''
220 >>> print f.__doc__
221 Backslashes in a raw docstring: m\n
222
Tim Peters8a7d2d52001-01-16 07:10:57 +0000223The starting column doesn't matter:
224
225>>> assert "Easy!"
226 >>> import math
227 >>> math.floor(1.9)
228 1.0
229
230and as many leading whitespace characters are stripped from the expected
231output as appeared in the initial ">>>" line that triggered it.
232
233If you execute this very file, the examples above will be found and
234executed, leading to this output in verbose mode:
235
236Running doctest.__doc__
Tim Peters60e23f42001-02-14 00:43:21 +0000237Trying: [1, 2, 3].remove(42)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000238Expecting:
Tim Petersea4f9312001-02-13 20:54:42 +0000239Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000240 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000241ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000242ok
243Trying: x = 12
244Expecting: nothing
245ok
246Trying: x
247Expecting: 12
248ok
249Trying:
250if x == 13:
251 print "yes"
252else:
253 print "no"
254 print "NO"
255 print "NO!!!"
256Expecting:
257no
258NO
259NO!!!
260ok
261... and a bunch more like that, with this summary at the end:
262
2635 items had no tests:
264 doctest.Tester.__init__
265 doctest.Tester.run__test__
266 doctest.Tester.summarize
267 doctest.run_docstring_examples
268 doctest.testmod
26912 items passed all tests:
270 8 tests in doctest
271 6 tests in doctest.Tester
272 10 tests in doctest.Tester.merge
Tim Peters17111f32001-10-03 04:08:26 +0000273 14 tests in doctest.Tester.rundict
Tim Peters8a7d2d52001-01-16 07:10:57 +0000274 3 tests in doctest.Tester.rundoc
275 3 tests in doctest.Tester.runstring
276 2 tests in doctest.__test__._TestClass
277 2 tests in doctest.__test__._TestClass.__init__
278 2 tests in doctest.__test__._TestClass.get
279 1 tests in doctest.__test__._TestClass.square
280 2 tests in doctest.__test__.string
281 7 tests in doctest.is_private
Tim Peters17111f32001-10-03 04:08:26 +000028260 tests in 17 items.
28360 passed and 0 failed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000284Test passed.
285"""
286
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000287__all__ = [
288 'testmod',
289 'run_docstring_examples',
290 'is_private',
291 'Tester',
Tim Petersdb3756d2003-06-29 05:30:48 +0000292 'DocTestTestFailure',
293 'DocTestSuite',
294 'testsource',
295 'debug',
Raymond Hettingercc39a132003-07-11 22:36:52 +0000296 'master',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000297]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000298
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000299import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000300
Tim Peters8a7d2d52001-01-16 07:10:57 +0000301import re
302PS1 = ">>>"
303PS2 = "..."
304_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
305_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
306_isEmpty = re.compile(r"\s*$").match
307_isComment = re.compile(r"\s*#").match
308del re
309
Tim Peters7402f792001-10-02 03:53:41 +0000310from types import StringTypes as _StringTypes
311
312from inspect import isclass as _isclass
313from inspect import isfunction as _isfunction
Raymond Hettinger5f8b0b12003-09-02 02:09:05 +0000314from inspect import ismethod as _ismethod
Tim Peters7402f792001-10-02 03:53:41 +0000315from inspect import ismodule as _ismodule
Tim Peters17111f32001-10-03 04:08:26 +0000316from inspect import classify_class_attrs as _classify_class_attrs
Tim Peters7402f792001-10-02 03:53:41 +0000317
Tim Peters6ebe61f2003-06-27 20:48:05 +0000318# Option constants.
319DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
320
Tim Peters8a7d2d52001-01-16 07:10:57 +0000321# Extract interactive examples from a string. Return a list of triples,
322# (source, outcome, lineno). "source" is the source code, and ends
323# with a newline iff the source spans more than one line. "outcome" is
324# the expected output if any, else an empty string. When not empty,
325# outcome always ends with a newline. "lineno" is the line number,
326# 0-based wrt the start of the string, of the first source line.
327
328def _extract_examples(s):
329 isPS1, isPS2 = _isPS1, _isPS2
330 isEmpty, isComment = _isEmpty, _isComment
331 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000332 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000333 i, n = 0, len(lines)
334 while i < n:
335 line = lines[i]
336 i = i + 1
337 m = isPS1(line)
338 if m is None:
339 continue
340 j = m.end(0) # beyond the prompt
341 if isEmpty(line, j) or isComment(line, j):
342 # a bare prompt or comment -- not interesting
343 continue
344 lineno = i - 1
345 if line[j] != " ":
Walter Dörwald70a6b492004-02-12 17:35:32 +0000346 raise ValueError("line %r of docstring lacks blank after %s: %s" %
347 (lineno, PS1, line))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000348 j = j + 1
349 blanks = m.group(1)
350 nblanks = len(blanks)
351 # suck up this and following PS2 lines
352 source = []
353 while 1:
354 source.append(line[j:])
355 line = lines[i]
356 m = isPS2(line)
357 if m:
358 if m.group(1) != blanks:
359 raise ValueError("inconsistent leading whitespace "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000360 "in line %r of docstring: %s" % (i, line))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000361 i = i + 1
362 else:
363 break
364 if len(source) == 1:
365 source = source[0]
366 else:
367 # get rid of useless null line from trailing empty "..."
368 if source[-1] == "":
369 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000370 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000371 # suck up response
372 if isPS1(line) or isEmpty(line):
373 expect = ""
374 else:
375 expect = []
376 while 1:
377 if line[:nblanks] != blanks:
378 raise ValueError("inconsistent leading whitespace "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000379 "in line %r of docstring: %s" % (i, line))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000380 expect.append(line[nblanks:])
381 i = i + 1
382 line = lines[i]
383 if isPS1(line) or isEmpty(line):
384 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000385 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000386 examples.append( (source, expect, lineno) )
387 return examples
388
389# Capture stdout when running examples.
390
391class _SpoofOut:
392 def __init__(self):
393 self.clear()
394 def write(self, s):
395 self.buf.append(s)
396 def get(self):
Tim Petersf9bb4962001-02-14 06:35:35 +0000397 guts = "".join(self.buf)
398 # If anything at all was written, make sure there's a trailing
399 # newline. There's no way for the expected output to indicate
400 # that a trailing newline is missing.
401 if guts and not guts.endswith("\n"):
402 guts = guts + "\n"
Tim Petersc77db342001-10-23 02:21:52 +0000403 # Prevent softspace from screwing up the next test case, in
404 # case they used print with a trailing comma in an example.
405 if hasattr(self, "softspace"):
406 del self.softspace
Tim Petersf9bb4962001-02-14 06:35:35 +0000407 return guts
Tim Peters8a7d2d52001-01-16 07:10:57 +0000408 def clear(self):
409 self.buf = []
Tim Petersc77db342001-10-23 02:21:52 +0000410 if hasattr(self, "softspace"):
411 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000412 def flush(self):
413 # JPython calls flush
414 pass
415
416# Display some tag-and-msg pairs nicely, keeping the tag and its msg
417# on the same line when that makes sense.
418
419def _tag_out(printer, *tag_msg_pairs):
420 for tag, msg in tag_msg_pairs:
421 printer(tag + ":")
422 msg_has_nl = msg[-1:] == "\n"
423 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000424 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000425 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
426 printer(" ")
427 else:
428 printer("\n")
429 printer(msg)
430 if not msg_has_nl:
431 printer("\n")
432
433# Run list of examples, in context globs. "out" can be used to display
434# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
435# that captures the examples' std output. Return (#failures, #tries).
436
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000437def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000438 compileflags, optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000439 import sys, traceback
440 OK, BOOM, FAIL = range(3)
441 NADA = "nothing"
442 stderr = _SpoofOut()
443 failures = 0
444 for source, want, lineno in examples:
445 if verbose:
446 _tag_out(out, ("Trying", source),
447 ("Expecting", want or NADA))
448 fakeout.clear()
449 try:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000450 exec compile(source, "<string>", "single",
451 compileflags, 1) in globs
Tim Peters8a7d2d52001-01-16 07:10:57 +0000452 got = fakeout.get()
453 state = OK
Tim Petersbcc2c122002-03-20 19:32:03 +0000454 except KeyboardInterrupt:
455 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000456 except:
457 # See whether the exception was expected.
Tim Petersea4f9312001-02-13 20:54:42 +0000458 if want.find("Traceback (innermost last):\n") == 0 or \
459 want.find("Traceback (most recent call last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000460 # Only compare exception type and value - the rest of
461 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000462 want = want.split('\n')[-2] + '\n'
Tim Peters77f2d502001-06-24 18:59:01 +0000463 exc_type, exc_val = sys.exc_info()[:2]
Tim Peters08bba952001-06-24 06:46:58 +0000464 got = traceback.format_exception_only(exc_type, exc_val)[-1]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000465 state = OK
466 else:
467 # unexpected exception
468 stderr.clear()
469 traceback.print_exc(file=stderr)
470 state = BOOM
471
472 if state == OK:
Tim Peters6ebe61f2003-06-27 20:48:05 +0000473 if (got == want or
474 (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and
475 (got, want) in (("True\n", "1\n"), ("False\n", "0\n"))
476 )
477 ):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000478 if verbose:
479 out("ok\n")
480 continue
481 state = FAIL
482
483 assert state in (FAIL, BOOM)
484 failures = failures + 1
485 out("*" * 65 + "\n")
486 _tag_out(out, ("Failure in example", source))
Walter Dörwald70a6b492004-02-12 17:35:32 +0000487 out("from line #%r of %s\n" % (lineno, name))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000488 if state == FAIL:
489 _tag_out(out, ("Expected", want or NADA), ("Got", got))
490 else:
491 assert state == BOOM
492 _tag_out(out, ("Exception raised", stderr.get()))
493
494 return failures, len(examples)
495
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000496# Get the future-flags associated with the future features that have been
497# imported into globs.
498
499def _extract_future_flags(globs):
500 flags = 0
501 for fname in __future__.all_feature_names:
502 feature = globs.get(fname, None)
503 if feature is getattr(__future__, fname):
504 flags |= feature.compiler_flag
505 return flags
506
Tim Petersd4ad59e2001-06-24 20:02:47 +0000507# Run list of examples, in a shallow copy of context (dict) globs.
508# Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000509
Tim Peters6ebe61f2003-06-27 20:48:05 +0000510def _run_examples(examples, globs, verbose, name, compileflags,
511 optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000512 import sys
513 saveout = sys.stdout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000514 globs = globs.copy()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000515 try:
516 sys.stdout = fakeout = _SpoofOut()
517 x = _run_examples_inner(saveout.write, fakeout, examples,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000518 globs, verbose, name, compileflags,
519 optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000520 finally:
521 sys.stdout = saveout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000522 # While Python gc can clean up most cycles on its own, it doesn't
523 # chase frame objects. This is especially irksome when running
524 # generator tests that raise exceptions, because a named generator-
525 # iterator gets an entry in globs, and the generator-iterator
526 # object's frame's traceback info points back to globs. This is
Tim Petersfee69d02001-06-24 20:24:16 +0000527 # easy to break just by clearing the namespace. This can also
528 # help to break other kinds of cycles, and even for cycles that
529 # gc can break itself it's better to break them ASAP.
Tim Petersd4ad59e2001-06-24 20:02:47 +0000530 globs.clear()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000531 return x
532
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000533def run_docstring_examples(f, globs, verbose=0, name="NoName",
Tim Peters6ebe61f2003-06-27 20:48:05 +0000534 compileflags=None, optionflags=0):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000535 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
536
Tim Petersd4ad59e2001-06-24 20:02:47 +0000537 Use (a shallow copy of) dict globs as the globals for execution.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000538 Return (#failures, #tries).
539
540 If optional arg verbose is true, print stuff even if there are no
541 failures.
542 Use string name in failure msgs.
543 """
544
545 try:
546 doc = f.__doc__
547 if not doc:
548 # docstring empty or None
549 return 0, 0
550 # just in case CT invents a doc object that has to be forced
551 # to look like a string <0.9 wink>
552 doc = str(doc)
Tim Petersbcc2c122002-03-20 19:32:03 +0000553 except KeyboardInterrupt:
554 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000555 except:
556 return 0, 0
557
558 e = _extract_examples(doc)
559 if not e:
560 return 0, 0
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000561 if compileflags is None:
562 compileflags = _extract_future_flags(globs)
Tim Peters6ebe61f2003-06-27 20:48:05 +0000563 return _run_examples(e, globs, verbose, name, compileflags, optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000564
565def is_private(prefix, base):
566 """prefix, base -> true iff name prefix + "." + base is "private".
567
568 Prefix may be an empty string, and base does not contain a period.
569 Prefix is ignored (although functions you write conforming to this
570 protocol may make use of it).
571 Return true iff base begins with an (at least one) underscore, but
572 does not both begin and end with (at least) two underscores.
573
574 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000575 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000576 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000577 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000578 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000579 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000580 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000581 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000582 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000583 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000584 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000585 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000586 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000587 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000588 """
589
590 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
591
Tim Peters7402f792001-10-02 03:53:41 +0000592# Determine if a class of function was defined in the given module.
593
594def _from_module(module, object):
595 if _isfunction(object):
596 return module.__dict__ is object.func_globals
597 if _isclass(object):
598 return module.__name__ == object.__module__
599 raise ValueError("object must be a class or function")
600
Tim Peters8a7d2d52001-01-16 07:10:57 +0000601class Tester:
602 """Class Tester -- runs docstring examples and accumulates stats.
603
604In normal use, function doctest.testmod() hides all this from you,
605so use that if you can. Create your own instances of Tester to do
606fancier things.
607
608Methods:
609 runstring(s, name)
610 Search string s for examples to run; use name for logging.
611 Return (#failures, #tries).
612
613 rundoc(object, name=None)
614 Search object.__doc__ for examples to run; use name (or
615 object.__name__) for logging. Return (#failures, #tries).
616
Tim Peters7402f792001-10-02 03:53:41 +0000617 rundict(d, name, module=None)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000618 Search for examples in docstrings in all of d.values(); use name
Tim Peters7402f792001-10-02 03:53:41 +0000619 for logging. Exclude functions and classes not defined in module
620 if specified. Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000621
622 run__test__(d, name)
623 Treat dict d like module.__test__. Return (#failures, #tries).
624
625 summarize(verbose=None)
626 Display summary of testing results, to stdout. Return
627 (#failures, #tries).
628
629 merge(other)
630 Merge in the test results from Tester instance "other".
631
632>>> from doctest import Tester
633>>> t = Tester(globs={'x': 42}, verbose=0)
634>>> t.runstring(r'''
635... >>> x = x * 2
636... >>> print x
637... 42
638... ''', 'XYZ')
639*****************************************************************
640Failure in example: print x
641from line #2 of XYZ
642Expected: 42
643Got: 84
644(1, 2)
645>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
646(0, 2)
647>>> t.summarize()
Guido van Rossum261d91a2001-03-18 17:05:58 +0000648*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006491 items had failures:
650 1 of 2 in XYZ
651***Test Failed*** 1 failures.
652(1, 4)
653>>> t.summarize(verbose=1)
6541 items passed all tests:
655 2 tests in example2
Guido van Rossum261d91a2001-03-18 17:05:58 +0000656*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006571 items had failures:
658 1 of 2 in XYZ
6594 tests in 2 items.
6603 passed and 1 failed.
661***Test Failed*** 1 failures.
662(1, 4)
663>>>
664"""
665
666 def __init__(self, mod=None, globs=None, verbose=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000667 isprivate=None, optionflags=0):
668 """mod=None, globs=None, verbose=None, isprivate=None,
669optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000670
671See doctest.__doc__ for an overview.
672
673Optional keyword arg "mod" is a module, whose globals are used for
674executing examples. If not specified, globs must be specified.
675
676Optional keyword arg "globs" gives a dict to be used as the globals
677when executing examples; if not specified, use the globals from
678module mod.
679
680In either case, a copy of the dict is used for each docstring
681examined.
682
683Optional keyword arg "verbose" prints lots of stuff if true, only
684failures if false; by default, it's true iff "-v" is in sys.argv.
685
686Optional keyword arg "isprivate" specifies a function used to determine
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000687whether a name is private. The default function is to assume that
688no functions are private. The "isprivate" arg may be set to
689doctest.is_private in order to skip over functions marked as private
690using an underscore naming convention; see its docs for details.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000691
692See doctest.testmod docs for the meaning of optionflags.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000693"""
694
695 if mod is None and globs is None:
696 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters7402f792001-10-02 03:53:41 +0000697 if mod is not None and not _ismodule(mod):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000698 raise TypeError("Tester.__init__: mod must be a module; %r" % (mod,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000699 if globs is None:
700 globs = mod.__dict__
701 self.globs = globs
702
703 if verbose is None:
704 import sys
705 verbose = "-v" in sys.argv
706 self.verbose = verbose
707
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000708 # By default, assume that nothing is private
Tim Peters8a7d2d52001-01-16 07:10:57 +0000709 if isprivate is None:
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000710 isprivate = lambda prefix, base: 0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000711 self.isprivate = isprivate
712
Tim Peters6ebe61f2003-06-27 20:48:05 +0000713 self.optionflags = optionflags
714
Tim Peters8a7d2d52001-01-16 07:10:57 +0000715 self.name2ft = {} # map name to (#failures, #trials) pair
716
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000717 self.compileflags = _extract_future_flags(globs)
718
Tim Peters8a7d2d52001-01-16 07:10:57 +0000719 def runstring(self, s, name):
720 """
721 s, name -> search string s for examples to run, logging as name.
722
723 Use string name as the key for logging the outcome.
724 Return (#failures, #examples).
725
726 >>> t = Tester(globs={}, verbose=1)
727 >>> test = r'''
728 ... # just an example
729 ... >>> x = 1 + 2
730 ... >>> x
731 ... 3
732 ... '''
733 >>> t.runstring(test, "Example")
734 Running string Example
735 Trying: x = 1 + 2
736 Expecting: nothing
737 ok
738 Trying: x
739 Expecting: 3
740 ok
741 0 of 2 examples failed in string Example
742 (0, 2)
743 """
744
745 if self.verbose:
746 print "Running string", name
747 f = t = 0
748 e = _extract_examples(s)
749 if e:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000750 f, t = _run_examples(e, self.globs, self.verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000751 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000752 if self.verbose:
753 print f, "of", t, "examples failed in string", name
754 self.__record_outcome(name, f, t)
755 return f, t
756
757 def rundoc(self, object, name=None):
758 """
759 object, name=None -> search object.__doc__ for examples to run.
760
761 Use optional string name as the key for logging the outcome;
762 by default use object.__name__.
763 Return (#failures, #examples).
764 If object is a class object, search recursively for method
765 docstrings too.
766 object.__doc__ is examined regardless of name, but if object is
767 a class, whether private names reached from object are searched
768 depends on the constructor's "isprivate" argument.
769
770 >>> t = Tester(globs={}, verbose=0)
771 >>> def _f():
772 ... '''Trivial docstring example.
773 ... >>> assert 2 == 2
774 ... '''
775 ... return 32
776 ...
777 >>> t.rundoc(_f) # expect 0 failures in 1 example
778 (0, 1)
779 """
780
781 if name is None:
782 try:
783 name = object.__name__
784 except AttributeError:
785 raise ValueError("Tester.rundoc: name must be given "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000786 "when object.__name__ doesn't exist; %r" % (object,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000787 if self.verbose:
788 print "Running", name + ".__doc__"
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000789 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
Tim Peters275abbd2003-06-29 03:11:20 +0000790 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000791 if self.verbose:
792 print f, "of", t, "examples failed in", name + ".__doc__"
793 self.__record_outcome(name, f, t)
Tim Peters7402f792001-10-02 03:53:41 +0000794 if _isclass(object):
Tim Peters17111f32001-10-03 04:08:26 +0000795 # In 2.2, class and static methods complicate life. Build
796 # a dict "that works", by hook or by crook.
797 d = {}
798 for tag, kind, homecls, value in _classify_class_attrs(object):
799
800 if homecls is not object:
801 # Only look at names defined immediately by the class.
802 continue
803
804 elif self.isprivate(name, tag):
805 continue
806
807 elif kind == "method":
808 # value is already a function
809 d[tag] = value
810
811 elif kind == "static method":
812 # value isn't a function, but getattr reveals one
813 d[tag] = getattr(object, tag)
814
815 elif kind == "class method":
816 # Hmm. A classmethod object doesn't seem to reveal
817 # enough. But getattr turns it into a bound method,
818 # and from there .im_func retrieves the underlying
819 # function.
820 d[tag] = getattr(object, tag).im_func
821
822 elif kind == "property":
823 # The methods implementing the property have their
824 # own docstrings -- but the property may have one too.
825 if value.__doc__ is not None:
826 d[tag] = str(value.__doc__)
827
828 elif kind == "data":
829 # Grab nested classes.
830 if _isclass(value):
831 d[tag] = value
832
833 else:
834 raise ValueError("teach doctest about %r" % kind)
835
836 f2, t2 = self.run__test__(d, name)
837 f += f2
838 t += t2
839
Tim Peters8a7d2d52001-01-16 07:10:57 +0000840 return f, t
841
Tim Peters7402f792001-10-02 03:53:41 +0000842 def rundict(self, d, name, module=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000843 """
Tim Peters7402f792001-10-02 03:53:41 +0000844 d, name, module=None -> search for docstring examples in d.values().
Tim Peters8a7d2d52001-01-16 07:10:57 +0000845
846 For k, v in d.items() such that v is a function or class,
847 do self.rundoc(v, name + "." + k). Whether this includes
848 objects with private names depends on the constructor's
Tim Peters7402f792001-10-02 03:53:41 +0000849 "isprivate" argument. If module is specified, functions and
850 classes that are not defined in module are excluded.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000851 Return aggregate (#failures, #examples).
852
Tim Peters7402f792001-10-02 03:53:41 +0000853 Build and populate two modules with sample functions to test that
854 exclusion of external functions and classes works.
855
856 >>> import new
857 >>> m1 = new.module('_m1')
858 >>> m2 = new.module('_m2')
859 >>> test_data = \"""
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000860 ... def _f():
Tim Peters7402f792001-10-02 03:53:41 +0000861 ... '''>>> assert 1 == 1
862 ... '''
863 ... def g():
Tim Peters8a7d2d52001-01-16 07:10:57 +0000864 ... '''>>> assert 2 != 1
865 ... '''
Tim Peters7402f792001-10-02 03:53:41 +0000866 ... class H:
867 ... '''>>> assert 2 > 1
868 ... '''
869 ... def bar(self):
870 ... '''>>> assert 1 < 2
871 ... '''
872 ... \"""
873 >>> exec test_data in m1.__dict__
874 >>> exec test_data in m2.__dict__
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000875 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tim Peters7402f792001-10-02 03:53:41 +0000876
877 Tests that objects outside m1 are excluded:
878
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000879 >>> t = Tester(globs={}, verbose=0, isprivate=is_private)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000880 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000881 (0, 3)
882
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000883 Again, but with the default isprivate function allowing _f:
Tim Peters7402f792001-10-02 03:53:41 +0000884
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000885 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000886 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000887 (0, 4)
888
889 And once more, not excluding stuff outside m1:
890
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000891 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000892 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Tim Peters7402f792001-10-02 03:53:41 +0000893 (0, 8)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000894
895 The exclusion of objects from outside the designated module is
896 meant to be invoked automagically by testmod.
897
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000898 >>> testmod(m1, isprivate=is_private)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000899 (0, 3)
900
Tim Peters8a7d2d52001-01-16 07:10:57 +0000901 """
902
903 if not hasattr(d, "items"):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000904 raise TypeError("Tester.rundict: d must support .items(); %r" % (d,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000905 f = t = 0
Tim Peters24a41912001-03-21 23:07:59 +0000906 # Run the tests by alpha order of names, for consistency in
907 # verbose-mode output.
908 names = d.keys()
909 names.sort()
910 for thisname in names:
911 value = d[thisname]
Tim Peters7402f792001-10-02 03:53:41 +0000912 if _isfunction(value) or _isclass(value):
913 if module and not _from_module(module, value):
914 continue
Tim Peters8a7d2d52001-01-16 07:10:57 +0000915 f2, t2 = self.__runone(value, name + "." + thisname)
916 f = f + f2
917 t = t + t2
918 return f, t
919
920 def run__test__(self, d, name):
921 """d, name -> Treat dict d like module.__test__.
922
923 Return (#failures, #tries).
924 See testmod.__doc__ for details.
925 """
926
927 failures = tries = 0
928 prefix = name + "."
929 savepvt = self.isprivate
930 try:
931 self.isprivate = lambda *args: 0
Tim Peters24a41912001-03-21 23:07:59 +0000932 # Run the tests by alpha order of names, for consistency in
933 # verbose-mode output.
934 keys = d.keys()
935 keys.sort()
936 for k in keys:
937 v = d[k]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000938 thisname = prefix + k
Tim Peters7402f792001-10-02 03:53:41 +0000939 if type(v) in _StringTypes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000940 f, t = self.runstring(v, thisname)
Raymond Hettinger5f8b0b12003-09-02 02:09:05 +0000941 elif _isfunction(v) or _isclass(v) or _ismethod(v):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000942 f, t = self.rundoc(v, thisname)
943 else:
944 raise TypeError("Tester.run__test__: values in "
Raymond Hettinger5f8b0b12003-09-02 02:09:05 +0000945 "dict must be strings, functions, methods, "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000946 "or classes; %r" % (v,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000947 failures = failures + f
948 tries = tries + t
949 finally:
950 self.isprivate = savepvt
951 return failures, tries
952
953 def summarize(self, verbose=None):
954 """
955 verbose=None -> summarize results, return (#failures, #tests).
956
957 Print summary of test results to stdout.
958 Optional arg 'verbose' controls how wordy this is. By
959 default, use the verbose setting established by the
960 constructor.
961 """
962
963 if verbose is None:
964 verbose = self.verbose
965 notests = []
966 passed = []
967 failed = []
968 totalt = totalf = 0
969 for x in self.name2ft.items():
970 name, (f, t) = x
971 assert f <= t
972 totalt = totalt + t
973 totalf = totalf + f
974 if t == 0:
975 notests.append(name)
976 elif f == 0:
977 passed.append( (name, t) )
978 else:
979 failed.append(x)
980 if verbose:
981 if notests:
982 print len(notests), "items had no tests:"
983 notests.sort()
984 for thing in notests:
985 print " ", thing
986 if passed:
987 print len(passed), "items passed all tests:"
988 passed.sort()
989 for thing, count in passed:
990 print " %3d tests in %s" % (count, thing)
991 if failed:
Guido van Rossumaf00a462001-03-18 16:58:44 +0000992 print "*" * 65
Tim Peters8a7d2d52001-01-16 07:10:57 +0000993 print len(failed), "items had failures:"
994 failed.sort()
995 for thing, (f, t) in failed:
996 print " %3d of %3d in %s" % (f, t, thing)
997 if verbose:
998 print totalt, "tests in", len(self.name2ft), "items."
999 print totalt - totalf, "passed and", totalf, "failed."
1000 if totalf:
1001 print "***Test Failed***", totalf, "failures."
1002 elif verbose:
1003 print "Test passed."
1004 return totalf, totalt
1005
1006 def merge(self, other):
1007 """
1008 other -> merge in test results from the other Tester instance.
1009
1010 If self and other both have a test result for something
1011 with the same name, the (#failures, #tests) results are
1012 summed, and a warning is printed to stdout.
1013
1014 >>> from doctest import Tester
1015 >>> t1 = Tester(globs={}, verbose=0)
1016 >>> t1.runstring('''
1017 ... >>> x = 12
1018 ... >>> print x
1019 ... 12
1020 ... ''', "t1example")
1021 (0, 2)
1022 >>>
1023 >>> t2 = Tester(globs={}, verbose=0)
1024 >>> t2.runstring('''
1025 ... >>> x = 13
1026 ... >>> print x
1027 ... 13
1028 ... ''', "t2example")
1029 (0, 2)
1030 >>> common = ">>> assert 1 + 2 == 3\\n"
1031 >>> t1.runstring(common, "common")
1032 (0, 1)
1033 >>> t2.runstring(common, "common")
1034 (0, 1)
1035 >>> t1.merge(t2)
1036 *** Tester.merge: 'common' in both testers; summing outcomes.
1037 >>> t1.summarize(1)
1038 3 items passed all tests:
1039 2 tests in common
1040 2 tests in t1example
1041 2 tests in t2example
1042 6 tests in 3 items.
1043 6 passed and 0 failed.
1044 Test passed.
1045 (0, 6)
1046 >>>
1047 """
1048
1049 d = self.name2ft
1050 for name, (f, t) in other.name2ft.items():
Raymond Hettinger54f02222002-06-01 14:18:47 +00001051 if name in d:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001052 print "*** Tester.merge: '" + name + "' in both" \
1053 " testers; summing outcomes."
1054 f2, t2 = d[name]
1055 f = f + f2
1056 t = t + t2
1057 d[name] = f, t
1058
1059 def __record_outcome(self, name, f, t):
Raymond Hettinger54f02222002-06-01 14:18:47 +00001060 if name in self.name2ft:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001061 print "*** Warning: '" + name + "' was tested before;", \
1062 "summing outcomes."
1063 f2, t2 = self.name2ft[name]
1064 f = f + f2
1065 t = t + t2
1066 self.name2ft[name] = f, t
1067
1068 def __runone(self, target, name):
1069 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +00001070 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001071 prefix, base = name[:i], name[i+1:]
1072 else:
1073 prefix, base = "", base
1074 if self.isprivate(prefix, base):
1075 return 0, 0
1076 return self.rundoc(target, name)
1077
1078master = None
1079
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001080def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +00001081 report=True, optionflags=0):
1082 """m=None, name=None, globs=None, verbose=None, isprivate=None,
1083 report=True, optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +00001084
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001085 Test examples in docstrings in functions and classes reachable
1086 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001087 with m.__doc__. Unless isprivate is specified, private names
1088 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001089
1090 Also test examples reachable from dict m.__test__ if it exists and is
1091 not None. m.__dict__ maps names to functions, classes and strings;
1092 function and class docstrings are tested even if the name is private;
1093 strings are tested directly, as if they were docstrings.
1094
1095 Return (#failures, #tests).
1096
1097 See doctest.__doc__ for an overview.
1098
1099 Optional keyword arg "name" gives the name of the module; by default
1100 use m.__name__.
1101
1102 Optional keyword arg "globs" gives a dict to be used as the globals
1103 when executing examples; by default, use m.__dict__. A copy of this
1104 dict is actually used for each docstring, so that each docstring's
1105 examples start with a clean slate.
1106
1107 Optional keyword arg "verbose" prints lots of stuff if true, prints
1108 only failures if false; by default, it's true iff "-v" is in sys.argv.
1109
1110 Optional keyword arg "isprivate" specifies a function used to
1111 determine whether a name is private. The default function is
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001112 treat all functions as public. Optionally, "isprivate" can be
1113 set to doctest.is_private to skip over functions marked as private
1114 using the underscore naming convention; see its docs for details.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001115
1116 Optional keyword arg "report" prints a summary at the end when true,
1117 else prints nothing at the end. In verbose mode, the summary is
1118 detailed, else very brief (in fact, empty if all tests passed).
1119
Tim Peters6ebe61f2003-06-27 20:48:05 +00001120 Optional keyword arg "optionflags" or's together module constants,
1121 and defaults to 0. This is new in 2.3. Possible values:
1122
1123 DONT_ACCEPT_TRUE_FOR_1
1124 By default, if an expected output block contains just "1",
1125 an actual output block containing just "True" is considered
1126 to be a match, and similarly for "0" versus "False". When
1127 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1128 is allowed.
1129
Tim Peters8a7d2d52001-01-16 07:10:57 +00001130 Advanced tomfoolery: testmod runs methods of a local instance of
1131 class doctest.Tester, then merges the results into (or creates)
1132 global Tester instance doctest.master. Methods of doctest.master
1133 can be called directly too, if you want to do something unusual.
1134 Passing report=0 to testmod is especially useful then, to delay
1135 displaying a summary. Invoke doctest.master.summarize(verbose)
1136 when you're done fiddling.
1137 """
1138
1139 global master
1140
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001141 if m is None:
1142 import sys
1143 # DWA - m will still be None if this wasn't invoked from the command
1144 # line, in which case the following TypeError is about as good an error
1145 # as we should expect
1146 m = sys.modules.get('__main__')
1147
Tim Peters7402f792001-10-02 03:53:41 +00001148 if not _ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001149 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001150 if name is None:
1151 name = m.__name__
Tim Peters6ebe61f2003-06-27 20:48:05 +00001152 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
1153 optionflags=optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001154 failures, tries = tester.rundoc(m, name)
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001155 f, t = tester.rundict(m.__dict__, name, m)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001156 failures += f
1157 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001158 if hasattr(m, "__test__"):
1159 testdict = m.__test__
1160 if testdict:
1161 if not hasattr(testdict, "items"):
1162 raise TypeError("testmod: module.__test__ must support "
Walter Dörwald70a6b492004-02-12 17:35:32 +00001163 ".items(); %r" % (testdict,))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001164 f, t = tester.run__test__(testdict, name + ".__test__")
Tim Peters6ebe61f2003-06-27 20:48:05 +00001165 failures += f
1166 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001167 if report:
1168 tester.summarize()
1169 if master is None:
1170 master = tester
1171 else:
1172 master.merge(tester)
1173 return failures, tries
1174
Tim Petersdb3756d2003-06-29 05:30:48 +00001175###########################################################################
1176# Various doctest extensions, to make using doctest with unittest
1177# easier, and to help debugging when a doctest goes wrong. Original
1178# code by Jim Fulton.
1179
1180# Utilities.
1181
1182# If module is None, return the calling module (the module that called
1183# the routine that called _normalize_module -- this normally won't be
1184# doctest!). If module is a string, it should be the (possibly dotted)
1185# name of a module, and the (rightmost) module object is returned. Else
1186# module is returned untouched; the intent appears to be that module is
1187# already a module object in this case (although this isn't checked).
1188
1189def _normalize_module(module):
1190 import sys
1191
1192 if module is None:
1193 # Get our caller's caller's module.
1194 module = sys._getframe(2).f_globals['__name__']
1195 module = sys.modules[module]
1196
Raymond Hettinger7a70ea42003-09-17 05:50:59 +00001197 elif isinstance(module, basestring):
Tim Petersdb3756d2003-06-29 05:30:48 +00001198 # The ["*"] at the end is a mostly meaningless incantation with
1199 # a crucial property: if, e.g., module is 'a.b.c', it convinces
1200 # __import__ to return c instead of a.
1201 module = __import__(module, globals(), locals(), ["*"])
1202
1203 return module
1204
1205# tests is a list of (testname, docstring, filename, lineno) tuples.
1206# If object has a __doc__ attr, and the __doc__ attr looks like it
1207# contains a doctest (specifically, if it contains an instance of '>>>'),
1208# then tuple
1209# prefix + name, object.__doc__, filename, lineno
1210# is appended to tests. Else tests is left alone.
1211# There is no return value.
1212
1213def _get_doctest(name, object, tests, prefix, filename='', lineno=''):
1214 doc = getattr(object, '__doc__', '')
1215 if isinstance(doc, basestring) and '>>>' in doc:
1216 tests.append((prefix + name, doc, filename, lineno))
1217
1218# tests is a list of (testname, docstring, filename, lineno) tuples.
1219# docstrings containing doctests are appended to tests (if any are found).
1220# items is a dict, like a module or class dict, mapping strings to objects.
1221# mdict is the global dict of a "home" module -- only objects belonging
1222# to this module are searched for docstrings. module is the module to
1223# which mdict belongs.
1224# prefix is a string to be prepended to an object's name when adding a
1225# tuple to tests.
1226# The objects (values) in items are examined (recursively), and doctests
1227# belonging to functions and classes in the home module are appended to
1228# tests.
1229# minlineno is a gimmick to try to guess the file-relative line number
1230# at which a doctest probably begins.
1231
1232def _extract_doctests(items, module, mdict, tests, prefix, minlineno=0):
1233
1234 for name, object in items:
1235 # Only interested in named objects.
1236 if not hasattr(object, '__name__'):
1237 continue
1238
1239 elif hasattr(object, 'func_globals'):
1240 # Looks like a function.
1241 if object.func_globals is not mdict:
1242 # Non-local function.
1243 continue
1244 code = getattr(object, 'func_code', None)
1245 filename = getattr(code, 'co_filename', '')
1246 lineno = getattr(code, 'co_firstlineno', -1) + 1
1247 if minlineno:
1248 minlineno = min(lineno, minlineno)
1249 else:
1250 minlineno = lineno
1251 _get_doctest(name, object, tests, prefix, filename, lineno)
1252
1253 elif hasattr(object, "__module__"):
1254 # Maybe a class-like thing, in which case we care.
1255 if object.__module__ != module.__name__:
1256 # Not the same module.
1257 continue
1258 if not (hasattr(object, '__dict__')
1259 and hasattr(object, '__bases__')):
1260 # Not a class.
1261 continue
1262
1263 lineno = _extract_doctests(object.__dict__.items(),
1264 module,
1265 mdict,
1266 tests,
1267 prefix + name + ".")
1268 # XXX "-3" is unclear.
1269 _get_doctest(name, object, tests, prefix,
1270 lineno="%s (or above)" % (lineno - 3))
1271
1272 return minlineno
1273
1274# Find all the doctests belonging to the module object.
1275# Return a list of
1276# (testname, docstring, filename, lineno)
1277# tuples.
1278
1279def _find_tests(module, prefix=None):
1280 if prefix is None:
1281 prefix = module.__name__
1282 mdict = module.__dict__
1283 tests = []
1284 # Get the module-level doctest (if any).
1285 _get_doctest(prefix, module, tests, '', lineno="1 (or above)")
1286 # Recursively search the module __dict__ for doctests.
1287 if prefix:
1288 prefix += "."
1289 _extract_doctests(mdict.items(), module, mdict, tests, prefix)
1290 return tests
1291
1292# unittest helpers.
1293
1294# A function passed to unittest, for unittest to drive.
1295# tester is doctest Tester instance. doc is the docstring whose
1296# doctests are to be run.
1297
1298def _utest(tester, name, doc, filename, lineno):
1299 import sys
1300 from StringIO import StringIO
1301
1302 old = sys.stdout
1303 sys.stdout = new = StringIO()
1304 try:
1305 failures, tries = tester.runstring(doc, name)
1306 finally:
1307 sys.stdout = old
1308
1309 if failures:
1310 msg = new.getvalue()
1311 lname = '.'.join(name.split('.')[-1:])
1312 if not lineno:
1313 lineno = "0 (don't know line number)"
1314 # Don't change this format! It was designed so that Emacs can
1315 # parse it naturally.
1316 raise DocTestTestFailure('Failed doctest test for %s\n'
1317 ' File "%s", line %s, in %s\n\n%s' %
1318 (name, filename, lineno, lname, msg))
1319
1320class DocTestTestFailure(Exception):
1321 """A doctest test failed"""
1322
1323def DocTestSuite(module=None):
1324 """Convert doctest tests for a module to a unittest TestSuite.
1325
1326 The returned TestSuite is to be run by the unittest framework, and
1327 runs each doctest in the module. If any of the doctests fail,
1328 then the synthesized unit test fails, and an error is raised showing
1329 the name of the file containing the test and a (sometimes approximate)
1330 line number.
1331
1332 The optional module argument provides the module to be tested. It
1333 can be a module object or a (possibly dotted) module name. If not
1334 specified, the module calling DocTestSuite() is used.
1335
1336 Example (although note that unittest supplies many ways to use the
1337 TestSuite returned; see the unittest docs):
1338
1339 import unittest
1340 import doctest
1341 import my_module_with_doctests
1342
1343 suite = doctest.DocTestSuite(my_module_with_doctests)
1344 runner = unittest.TextTestRunner()
1345 runner.run(suite)
1346 """
1347
1348 import unittest
1349
1350 module = _normalize_module(module)
1351 tests = _find_tests(module)
1352 if not tests:
1353 raise ValueError(module, "has no tests")
1354
1355 tests.sort()
1356 suite = unittest.TestSuite()
1357 tester = Tester(module)
1358 for name, doc, filename, lineno in tests:
1359 if not filename:
1360 filename = module.__file__
1361 if filename.endswith(".pyc"):
1362 filename = filename[:-1]
1363 elif filename.endswith(".pyo"):
1364 filename = filename[:-1]
1365 def runit(name=name, doc=doc, filename=filename, lineno=lineno):
1366 _utest(tester, name, doc, filename, lineno)
1367 suite.addTest(unittest.FunctionTestCase(
1368 runit,
1369 description="doctest of " + name))
1370 return suite
1371
1372# Debugging support.
1373
1374def _expect(expect):
1375 # Return the expected output (if any), formatted as a Python
1376 # comment block.
1377 if expect:
1378 expect = "\n# ".join(expect.split("\n"))
1379 expect = "\n# Expect:\n# %s" % expect
1380 return expect
1381
1382def testsource(module, name):
1383 """Extract the doctest examples from a docstring.
1384
1385 Provide the module (or dotted name of the module) containing the
1386 tests to be extracted, and the name (within the module) of the object
1387 with the docstring containing the tests to be extracted.
1388
1389 The doctest examples are returned as a string containing Python
1390 code. The expected output blocks in the examples are converted
1391 to Python comments.
1392 """
1393
1394 module = _normalize_module(module)
1395 tests = _find_tests(module, "")
1396 test = [doc for (tname, doc, dummy, dummy) in tests
1397 if tname == name]
1398 if not test:
1399 raise ValueError(name, "not found in tests")
1400 test = test[0]
1401 examples = [source + _expect(expect)
1402 for source, expect, dummy in _extract_examples(test)]
1403 return '\n'.join(examples)
1404
1405def debug(module, name):
1406 """Debug a single docstring containing doctests.
1407
1408 Provide the module (or dotted name of the module) containing the
1409 docstring to be debugged, and the name (within the module) of the
1410 object with the docstring to be debugged.
1411
1412 The doctest examples are extracted (see function testsource()),
1413 and written to a temp file. The Python debugger (pdb) is then
1414 invoked on that file.
1415 """
1416
1417 import os
1418 import pdb
1419 import tempfile
1420
1421 module = _normalize_module(module)
1422 testsrc = testsource(module, name)
1423 srcfilename = tempfile.mktemp("doctestdebug.py")
1424 f = file(srcfilename, 'w')
1425 f.write(testsrc)
1426 f.close()
1427
1428 globs = {}
1429 globs.update(module.__dict__)
1430 try:
1431 # Note that %r is vital here. '%s' instead can, e.g., cause
1432 # backslashes to get treated as metacharacters on Windows.
1433 pdb.run("execfile(%r)" % srcfilename, globs, globs)
1434 finally:
1435 os.remove(srcfilename)
1436
1437
1438
Tim Peters8a7d2d52001-01-16 07:10:57 +00001439class _TestClass:
1440 """
1441 A pointless class, for sanity-checking of docstring testing.
1442
1443 Methods:
1444 square()
1445 get()
1446
1447 >>> _TestClass(13).get() + _TestClass(-12).get()
1448 1
1449 >>> hex(_TestClass(13).square().get())
1450 '0xa9'
1451 """
1452
1453 def __init__(self, val):
1454 """val -> _TestClass object with associated value val.
1455
1456 >>> t = _TestClass(123)
1457 >>> print t.get()
1458 123
1459 """
1460
1461 self.val = val
1462
1463 def square(self):
1464 """square() -> square TestClass's associated value
1465
1466 >>> _TestClass(13).square().get()
1467 169
1468 """
1469
1470 self.val = self.val ** 2
1471 return self
1472
1473 def get(self):
1474 """get() -> return TestClass's associated value.
1475
1476 >>> x = _TestClass(-42)
1477 >>> print x.get()
1478 -42
1479 """
1480
1481 return self.val
1482
1483__test__ = {"_TestClass": _TestClass,
1484 "string": r"""
1485 Example of a string object, searched as-is.
1486 >>> x = 1; y = 2
1487 >>> x + y, x * y
1488 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001489 """,
1490 "bool-int equivalence": r"""
1491 In 2.2, boolean expressions displayed
1492 0 or 1. By default, we still accept
1493 them. This can be disabled by passing
1494 DONT_ACCEPT_TRUE_FOR_1 to the new
1495 optionflags argument.
1496 >>> 4 == 4
1497 1
1498 >>> 4 == 4
1499 True
1500 >>> 4 > 4
1501 0
1502 >>> 4 > 4
1503 False
1504 """,
Tim Peters8a7d2d52001-01-16 07:10:57 +00001505 }
1506
1507def _test():
1508 import doctest
1509 return doctest.testmod(doctest)
1510
1511if __name__ == "__main__":
1512 _test()