blob: 69047db516de6f3588636913ff1360f8db47f115 [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
Tim Peters4e0e1b62004-07-07 20:54:48 +0000208 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000209 ... 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
Tim Peters4e0e1b62004-07-07 20:54:48 +0000218 >>> def f(x):
Martin v. Löwis92816de2004-05-31 19:01:00 +0000219 ... '''Backslashes in a raw docstring: m\\n'''
220 >>> print f.__doc__
221 Backslashes in a raw docstring: m\n
Tim Peters4e0e1b62004-07-07 20:54:48 +0000222
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 'DocTestSuite',
293 'testsource',
294 'debug',
Raymond Hettingercc39a132003-07-11 22:36:52 +0000295 'master',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000296]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000297
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000298import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000299
Tim Peters8a7d2d52001-01-16 07:10:57 +0000300import re
301PS1 = ">>>"
302PS2 = "..."
303_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
304_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
305_isEmpty = re.compile(r"\s*$").match
306_isComment = re.compile(r"\s*#").match
307del re
308
Tim Peters7402f792001-10-02 03:53:41 +0000309from types import StringTypes as _StringTypes
310
311from inspect import isclass as _isclass
312from inspect import isfunction as _isfunction
Raymond Hettinger5f8b0b12003-09-02 02:09:05 +0000313from inspect import ismethod as _ismethod
Tim Peters7402f792001-10-02 03:53:41 +0000314from inspect import ismodule as _ismodule
Tim Peters17111f32001-10-03 04:08:26 +0000315from inspect import classify_class_attrs as _classify_class_attrs
Tim Peters7402f792001-10-02 03:53:41 +0000316
Tim Peters6ebe61f2003-06-27 20:48:05 +0000317# Option constants.
318DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
319
Tim Peters8a7d2d52001-01-16 07:10:57 +0000320# Extract interactive examples from a string. Return a list of triples,
321# (source, outcome, lineno). "source" is the source code, and ends
322# with a newline iff the source spans more than one line. "outcome" is
323# the expected output if any, else an empty string. When not empty,
324# outcome always ends with a newline. "lineno" is the line number,
325# 0-based wrt the start of the string, of the first source line.
326
327def _extract_examples(s):
328 isPS1, isPS2 = _isPS1, _isPS2
329 isEmpty, isComment = _isEmpty, _isComment
330 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000331 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000332 i, n = 0, len(lines)
333 while i < n:
334 line = lines[i]
335 i = i + 1
336 m = isPS1(line)
337 if m is None:
338 continue
339 j = m.end(0) # beyond the prompt
340 if isEmpty(line, j) or isComment(line, j):
341 # a bare prompt or comment -- not interesting
342 continue
343 lineno = i - 1
344 if line[j] != " ":
Walter Dörwald70a6b492004-02-12 17:35:32 +0000345 raise ValueError("line %r of docstring lacks blank after %s: %s" %
346 (lineno, PS1, line))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000347 j = j + 1
348 blanks = m.group(1)
349 nblanks = len(blanks)
350 # suck up this and following PS2 lines
351 source = []
352 while 1:
353 source.append(line[j:])
354 line = lines[i]
355 m = isPS2(line)
356 if m:
357 if m.group(1) != blanks:
358 raise ValueError("inconsistent leading whitespace "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000359 "in line %r of docstring: %s" % (i, line))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000360 i = i + 1
361 else:
362 break
363 if len(source) == 1:
364 source = source[0]
365 else:
366 # get rid of useless null line from trailing empty "..."
367 if source[-1] == "":
368 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000369 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000370 # suck up response
371 if isPS1(line) or isEmpty(line):
372 expect = ""
373 else:
374 expect = []
375 while 1:
376 if line[:nblanks] != blanks:
377 raise ValueError("inconsistent leading whitespace "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000378 "in line %r of docstring: %s" % (i, line))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000379 expect.append(line[nblanks:])
380 i = i + 1
381 line = lines[i]
382 if isPS1(line) or isEmpty(line):
383 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000384 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000385 examples.append( (source, expect, lineno) )
386 return examples
387
388# Capture stdout when running examples.
389
390class _SpoofOut:
391 def __init__(self):
392 self.clear()
393 def write(self, s):
394 self.buf.append(s)
395 def get(self):
Tim Petersf9bb4962001-02-14 06:35:35 +0000396 guts = "".join(self.buf)
397 # If anything at all was written, make sure there's a trailing
398 # newline. There's no way for the expected output to indicate
399 # that a trailing newline is missing.
400 if guts and not guts.endswith("\n"):
401 guts = guts + "\n"
Tim Petersc77db342001-10-23 02:21:52 +0000402 # Prevent softspace from screwing up the next test case, in
403 # case they used print with a trailing comma in an example.
404 if hasattr(self, "softspace"):
405 del self.softspace
Tim Petersf9bb4962001-02-14 06:35:35 +0000406 return guts
Tim Peters8a7d2d52001-01-16 07:10:57 +0000407 def clear(self):
408 self.buf = []
Tim Petersc77db342001-10-23 02:21:52 +0000409 if hasattr(self, "softspace"):
410 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000411 def flush(self):
412 # JPython calls flush
413 pass
414
415# Display some tag-and-msg pairs nicely, keeping the tag and its msg
416# on the same line when that makes sense.
417
418def _tag_out(printer, *tag_msg_pairs):
419 for tag, msg in tag_msg_pairs:
420 printer(tag + ":")
421 msg_has_nl = msg[-1:] == "\n"
422 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000423 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000424 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
425 printer(" ")
426 else:
427 printer("\n")
428 printer(msg)
429 if not msg_has_nl:
430 printer("\n")
431
432# Run list of examples, in context globs. "out" can be used to display
433# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
434# that captures the examples' std output. Return (#failures, #tries).
435
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000436def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000437 compileflags, optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000438 import sys, traceback
439 OK, BOOM, FAIL = range(3)
440 NADA = "nothing"
441 stderr = _SpoofOut()
442 failures = 0
443 for source, want, lineno in examples:
444 if verbose:
445 _tag_out(out, ("Trying", source),
446 ("Expecting", want or NADA))
447 fakeout.clear()
448 try:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000449 exec compile(source, "<string>", "single",
450 compileflags, 1) in globs
Tim Peters8a7d2d52001-01-16 07:10:57 +0000451 got = fakeout.get()
452 state = OK
Tim Petersbcc2c122002-03-20 19:32:03 +0000453 except KeyboardInterrupt:
454 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000455 except:
456 # See whether the exception was expected.
Tim Petersea4f9312001-02-13 20:54:42 +0000457 if want.find("Traceback (innermost last):\n") == 0 or \
458 want.find("Traceback (most recent call last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000459 # Only compare exception type and value - the rest of
460 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000461 want = want.split('\n')[-2] + '\n'
Tim Peters77f2d502001-06-24 18:59:01 +0000462 exc_type, exc_val = sys.exc_info()[:2]
Tim Peters08bba952001-06-24 06:46:58 +0000463 got = traceback.format_exception_only(exc_type, exc_val)[-1]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000464 state = OK
465 else:
466 # unexpected exception
467 stderr.clear()
468 traceback.print_exc(file=stderr)
469 state = BOOM
470
471 if state == OK:
Tim Peters6ebe61f2003-06-27 20:48:05 +0000472 if (got == want or
473 (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and
474 (got, want) in (("True\n", "1\n"), ("False\n", "0\n"))
475 )
476 ):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000477 if verbose:
478 out("ok\n")
479 continue
480 state = FAIL
481
482 assert state in (FAIL, BOOM)
483 failures = failures + 1
484 out("*" * 65 + "\n")
485 _tag_out(out, ("Failure in example", source))
Walter Dörwald70a6b492004-02-12 17:35:32 +0000486 out("from line #%r of %s\n" % (lineno, name))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000487 if state == FAIL:
488 _tag_out(out, ("Expected", want or NADA), ("Got", got))
489 else:
490 assert state == BOOM
491 _tag_out(out, ("Exception raised", stderr.get()))
492
493 return failures, len(examples)
494
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000495# Get the future-flags associated with the future features that have been
496# imported into globs.
497
498def _extract_future_flags(globs):
499 flags = 0
500 for fname in __future__.all_feature_names:
501 feature = globs.get(fname, None)
502 if feature is getattr(__future__, fname):
503 flags |= feature.compiler_flag
504 return flags
505
Tim Petersd4ad59e2001-06-24 20:02:47 +0000506# Run list of examples, in a shallow copy of context (dict) globs.
507# Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000508
Tim Peters6ebe61f2003-06-27 20:48:05 +0000509def _run_examples(examples, globs, verbose, name, compileflags,
510 optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000511 import sys
512 saveout = sys.stdout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000513 globs = globs.copy()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000514 try:
515 sys.stdout = fakeout = _SpoofOut()
516 x = _run_examples_inner(saveout.write, fakeout, examples,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000517 globs, verbose, name, compileflags,
518 optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000519 finally:
520 sys.stdout = saveout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000521 # While Python gc can clean up most cycles on its own, it doesn't
522 # chase frame objects. This is especially irksome when running
523 # generator tests that raise exceptions, because a named generator-
524 # iterator gets an entry in globs, and the generator-iterator
525 # object's frame's traceback info points back to globs. This is
Tim Petersfee69d02001-06-24 20:24:16 +0000526 # easy to break just by clearing the namespace. This can also
527 # help to break other kinds of cycles, and even for cycles that
528 # gc can break itself it's better to break them ASAP.
Tim Petersd4ad59e2001-06-24 20:02:47 +0000529 globs.clear()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000530 return x
531
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000532def run_docstring_examples(f, globs, verbose=0, name="NoName",
Tim Peters6ebe61f2003-06-27 20:48:05 +0000533 compileflags=None, optionflags=0):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000534 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
535
Tim Petersd4ad59e2001-06-24 20:02:47 +0000536 Use (a shallow copy of) dict globs as the globals for execution.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000537 Return (#failures, #tries).
538
539 If optional arg verbose is true, print stuff even if there are no
540 failures.
541 Use string name in failure msgs.
542 """
543
544 try:
545 doc = f.__doc__
546 if not doc:
547 # docstring empty or None
548 return 0, 0
549 # just in case CT invents a doc object that has to be forced
550 # to look like a string <0.9 wink>
551 doc = str(doc)
Tim Petersbcc2c122002-03-20 19:32:03 +0000552 except KeyboardInterrupt:
553 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000554 except:
555 return 0, 0
556
557 e = _extract_examples(doc)
558 if not e:
559 return 0, 0
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000560 if compileflags is None:
561 compileflags = _extract_future_flags(globs)
Tim Peters6ebe61f2003-06-27 20:48:05 +0000562 return _run_examples(e, globs, verbose, name, compileflags, optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000563
564def is_private(prefix, base):
565 """prefix, base -> true iff name prefix + "." + base is "private".
566
567 Prefix may be an empty string, and base does not contain a period.
568 Prefix is ignored (although functions you write conforming to this
569 protocol may make use of it).
570 Return true iff base begins with an (at least one) underscore, but
571 does not both begin and end with (at least) two underscores.
572
573 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000574 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000575 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000576 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000577 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000578 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000579 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000580 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000581 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000582 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000583 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000584 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000585 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000586 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000587 """
588
589 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
590
Tim Peters7402f792001-10-02 03:53:41 +0000591# Determine if a class of function was defined in the given module.
592
593def _from_module(module, object):
594 if _isfunction(object):
595 return module.__dict__ is object.func_globals
596 if _isclass(object):
597 return module.__name__ == object.__module__
598 raise ValueError("object must be a class or function")
599
Tim Peters8a7d2d52001-01-16 07:10:57 +0000600class Tester:
601 """Class Tester -- runs docstring examples and accumulates stats.
602
603In normal use, function doctest.testmod() hides all this from you,
604so use that if you can. Create your own instances of Tester to do
605fancier things.
606
607Methods:
608 runstring(s, name)
609 Search string s for examples to run; use name for logging.
610 Return (#failures, #tries).
611
612 rundoc(object, name=None)
613 Search object.__doc__ for examples to run; use name (or
614 object.__name__) for logging. Return (#failures, #tries).
615
Tim Peters7402f792001-10-02 03:53:41 +0000616 rundict(d, name, module=None)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000617 Search for examples in docstrings in all of d.values(); use name
Tim Peters7402f792001-10-02 03:53:41 +0000618 for logging. Exclude functions and classes not defined in module
619 if specified. Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000620
621 run__test__(d, name)
622 Treat dict d like module.__test__. Return (#failures, #tries).
623
624 summarize(verbose=None)
625 Display summary of testing results, to stdout. Return
626 (#failures, #tries).
627
628 merge(other)
629 Merge in the test results from Tester instance "other".
630
631>>> from doctest import Tester
632>>> t = Tester(globs={'x': 42}, verbose=0)
633>>> t.runstring(r'''
634... >>> x = x * 2
635... >>> print x
636... 42
637... ''', 'XYZ')
638*****************************************************************
639Failure in example: print x
640from line #2 of XYZ
641Expected: 42
642Got: 84
643(1, 2)
644>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
645(0, 2)
646>>> t.summarize()
Guido van Rossum261d91a2001-03-18 17:05:58 +0000647*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006481 items had failures:
649 1 of 2 in XYZ
650***Test Failed*** 1 failures.
651(1, 4)
652>>> t.summarize(verbose=1)
6531 items passed all tests:
654 2 tests in example2
Guido van Rossum261d91a2001-03-18 17:05:58 +0000655*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006561 items had failures:
657 1 of 2 in XYZ
6584 tests in 2 items.
6593 passed and 1 failed.
660***Test Failed*** 1 failures.
661(1, 4)
662>>>
663"""
664
665 def __init__(self, mod=None, globs=None, verbose=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000666 isprivate=None, optionflags=0):
667 """mod=None, globs=None, verbose=None, isprivate=None,
668optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000669
670See doctest.__doc__ for an overview.
671
672Optional keyword arg "mod" is a module, whose globals are used for
673executing examples. If not specified, globs must be specified.
674
675Optional keyword arg "globs" gives a dict to be used as the globals
676when executing examples; if not specified, use the globals from
677module mod.
678
679In either case, a copy of the dict is used for each docstring
680examined.
681
682Optional keyword arg "verbose" prints lots of stuff if true, only
683failures if false; by default, it's true iff "-v" is in sys.argv.
684
685Optional keyword arg "isprivate" specifies a function used to determine
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000686whether a name is private. The default function is to assume that
687no functions are private. The "isprivate" arg may be set to
688doctest.is_private in order to skip over functions marked as private
689using an underscore naming convention; see its docs for details.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000690
691See doctest.testmod docs for the meaning of optionflags.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000692"""
693
694 if mod is None and globs is None:
695 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters7402f792001-10-02 03:53:41 +0000696 if mod is not None and not _ismodule(mod):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000697 raise TypeError("Tester.__init__: mod must be a module; %r" % (mod,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000698 if globs is None:
699 globs = mod.__dict__
700 self.globs = globs
701
702 if verbose is None:
703 import sys
704 verbose = "-v" in sys.argv
705 self.verbose = verbose
706
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000707 # By default, assume that nothing is private
Tim Peters8a7d2d52001-01-16 07:10:57 +0000708 if isprivate is None:
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000709 isprivate = lambda prefix, base: 0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000710 self.isprivate = isprivate
711
Tim Peters6ebe61f2003-06-27 20:48:05 +0000712 self.optionflags = optionflags
713
Tim Peters8a7d2d52001-01-16 07:10:57 +0000714 self.name2ft = {} # map name to (#failures, #trials) pair
715
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000716 self.compileflags = _extract_future_flags(globs)
717
Tim Peters8a7d2d52001-01-16 07:10:57 +0000718 def runstring(self, s, name):
719 """
720 s, name -> search string s for examples to run, logging as name.
721
722 Use string name as the key for logging the outcome.
723 Return (#failures, #examples).
724
725 >>> t = Tester(globs={}, verbose=1)
726 >>> test = r'''
727 ... # just an example
728 ... >>> x = 1 + 2
729 ... >>> x
730 ... 3
731 ... '''
732 >>> t.runstring(test, "Example")
733 Running string Example
734 Trying: x = 1 + 2
735 Expecting: nothing
736 ok
737 Trying: x
738 Expecting: 3
739 ok
740 0 of 2 examples failed in string Example
741 (0, 2)
742 """
743
744 if self.verbose:
745 print "Running string", name
746 f = t = 0
747 e = _extract_examples(s)
748 if e:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000749 f, t = _run_examples(e, self.globs, self.verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000750 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000751 if self.verbose:
752 print f, "of", t, "examples failed in string", name
753 self.__record_outcome(name, f, t)
754 return f, t
755
756 def rundoc(self, object, name=None):
757 """
758 object, name=None -> search object.__doc__ for examples to run.
759
760 Use optional string name as the key for logging the outcome;
761 by default use object.__name__.
762 Return (#failures, #examples).
763 If object is a class object, search recursively for method
764 docstrings too.
765 object.__doc__ is examined regardless of name, but if object is
766 a class, whether private names reached from object are searched
767 depends on the constructor's "isprivate" argument.
768
769 >>> t = Tester(globs={}, verbose=0)
770 >>> def _f():
771 ... '''Trivial docstring example.
772 ... >>> assert 2 == 2
773 ... '''
774 ... return 32
775 ...
776 >>> t.rundoc(_f) # expect 0 failures in 1 example
777 (0, 1)
778 """
779
780 if name is None:
781 try:
782 name = object.__name__
783 except AttributeError:
784 raise ValueError("Tester.rundoc: name must be given "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000785 "when object.__name__ doesn't exist; %r" % (object,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000786 if self.verbose:
787 print "Running", name + ".__doc__"
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000788 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
Tim Peters275abbd2003-06-29 03:11:20 +0000789 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000790 if self.verbose:
791 print f, "of", t, "examples failed in", name + ".__doc__"
792 self.__record_outcome(name, f, t)
Tim Peters7402f792001-10-02 03:53:41 +0000793 if _isclass(object):
Tim Peters17111f32001-10-03 04:08:26 +0000794 # In 2.2, class and static methods complicate life. Build
795 # a dict "that works", by hook or by crook.
796 d = {}
797 for tag, kind, homecls, value in _classify_class_attrs(object):
798
799 if homecls is not object:
800 # Only look at names defined immediately by the class.
801 continue
802
803 elif self.isprivate(name, tag):
804 continue
805
806 elif kind == "method":
807 # value is already a function
808 d[tag] = value
809
810 elif kind == "static method":
811 # value isn't a function, but getattr reveals one
812 d[tag] = getattr(object, tag)
813
814 elif kind == "class method":
815 # Hmm. A classmethod object doesn't seem to reveal
816 # enough. But getattr turns it into a bound method,
817 # and from there .im_func retrieves the underlying
818 # function.
819 d[tag] = getattr(object, tag).im_func
820
821 elif kind == "property":
822 # The methods implementing the property have their
823 # own docstrings -- but the property may have one too.
824 if value.__doc__ is not None:
825 d[tag] = str(value.__doc__)
826
827 elif kind == "data":
828 # Grab nested classes.
829 if _isclass(value):
830 d[tag] = value
831
832 else:
833 raise ValueError("teach doctest about %r" % kind)
834
835 f2, t2 = self.run__test__(d, name)
836 f += f2
837 t += t2
838
Tim Peters8a7d2d52001-01-16 07:10:57 +0000839 return f, t
840
Tim Peters7402f792001-10-02 03:53:41 +0000841 def rundict(self, d, name, module=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000842 """
Tim Peters7402f792001-10-02 03:53:41 +0000843 d, name, module=None -> search for docstring examples in d.values().
Tim Peters8a7d2d52001-01-16 07:10:57 +0000844
845 For k, v in d.items() such that v is a function or class,
846 do self.rundoc(v, name + "." + k). Whether this includes
847 objects with private names depends on the constructor's
Tim Peters7402f792001-10-02 03:53:41 +0000848 "isprivate" argument. If module is specified, functions and
849 classes that are not defined in module are excluded.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000850 Return aggregate (#failures, #examples).
851
Tim Peters7402f792001-10-02 03:53:41 +0000852 Build and populate two modules with sample functions to test that
853 exclusion of external functions and classes works.
854
855 >>> import new
856 >>> m1 = new.module('_m1')
857 >>> m2 = new.module('_m2')
858 >>> test_data = \"""
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000859 ... def _f():
Tim Peters7402f792001-10-02 03:53:41 +0000860 ... '''>>> assert 1 == 1
861 ... '''
862 ... def g():
Tim Peters8a7d2d52001-01-16 07:10:57 +0000863 ... '''>>> assert 2 != 1
864 ... '''
Tim Peters7402f792001-10-02 03:53:41 +0000865 ... class H:
866 ... '''>>> assert 2 > 1
867 ... '''
868 ... def bar(self):
869 ... '''>>> assert 1 < 2
870 ... '''
871 ... \"""
872 >>> exec test_data in m1.__dict__
873 >>> exec test_data in m2.__dict__
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000874 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tim Peters7402f792001-10-02 03:53:41 +0000875
876 Tests that objects outside m1 are excluded:
877
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000878 >>> t = Tester(globs={}, verbose=0, isprivate=is_private)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000879 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000880 (0, 3)
881
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000882 Again, but with the default isprivate function allowing _f:
Tim Peters7402f792001-10-02 03:53:41 +0000883
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000884 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000885 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000886 (0, 4)
887
888 And once more, not excluding stuff outside m1:
889
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000890 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000891 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Tim Peters7402f792001-10-02 03:53:41 +0000892 (0, 8)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000893
894 The exclusion of objects from outside the designated module is
895 meant to be invoked automagically by testmod.
896
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000897 >>> testmod(m1, isprivate=is_private)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000898 (0, 3)
899
Tim Peters8a7d2d52001-01-16 07:10:57 +0000900 """
901
902 if not hasattr(d, "items"):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000903 raise TypeError("Tester.rundict: d must support .items(); %r" % (d,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000904 f = t = 0
Tim Peters24a41912001-03-21 23:07:59 +0000905 # Run the tests by alpha order of names, for consistency in
906 # verbose-mode output.
907 names = d.keys()
908 names.sort()
909 for thisname in names:
910 value = d[thisname]
Tim Peters7402f792001-10-02 03:53:41 +0000911 if _isfunction(value) or _isclass(value):
912 if module and not _from_module(module, value):
913 continue
Tim Peters8a7d2d52001-01-16 07:10:57 +0000914 f2, t2 = self.__runone(value, name + "." + thisname)
915 f = f + f2
916 t = t + t2
917 return f, t
918
919 def run__test__(self, d, name):
920 """d, name -> Treat dict d like module.__test__.
921
922 Return (#failures, #tries).
923 See testmod.__doc__ for details.
924 """
925
926 failures = tries = 0
927 prefix = name + "."
928 savepvt = self.isprivate
929 try:
930 self.isprivate = lambda *args: 0
Tim Peters24a41912001-03-21 23:07:59 +0000931 # Run the tests by alpha order of names, for consistency in
932 # verbose-mode output.
933 keys = d.keys()
934 keys.sort()
935 for k in keys:
936 v = d[k]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000937 thisname = prefix + k
Tim Peters7402f792001-10-02 03:53:41 +0000938 if type(v) in _StringTypes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000939 f, t = self.runstring(v, thisname)
Raymond Hettinger5f8b0b12003-09-02 02:09:05 +0000940 elif _isfunction(v) or _isclass(v) or _ismethod(v):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000941 f, t = self.rundoc(v, thisname)
942 else:
943 raise TypeError("Tester.run__test__: values in "
Raymond Hettinger5f8b0b12003-09-02 02:09:05 +0000944 "dict must be strings, functions, methods, "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000945 "or classes; %r" % (v,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000946 failures = failures + f
947 tries = tries + t
948 finally:
949 self.isprivate = savepvt
950 return failures, tries
951
952 def summarize(self, verbose=None):
953 """
954 verbose=None -> summarize results, return (#failures, #tests).
955
956 Print summary of test results to stdout.
957 Optional arg 'verbose' controls how wordy this is. By
958 default, use the verbose setting established by the
959 constructor.
960 """
961
962 if verbose is None:
963 verbose = self.verbose
964 notests = []
965 passed = []
966 failed = []
967 totalt = totalf = 0
968 for x in self.name2ft.items():
969 name, (f, t) = x
970 assert f <= t
971 totalt = totalt + t
972 totalf = totalf + f
973 if t == 0:
974 notests.append(name)
975 elif f == 0:
976 passed.append( (name, t) )
977 else:
978 failed.append(x)
979 if verbose:
980 if notests:
981 print len(notests), "items had no tests:"
982 notests.sort()
983 for thing in notests:
984 print " ", thing
985 if passed:
986 print len(passed), "items passed all tests:"
987 passed.sort()
988 for thing, count in passed:
989 print " %3d tests in %s" % (count, thing)
990 if failed:
Guido van Rossumaf00a462001-03-18 16:58:44 +0000991 print "*" * 65
Tim Peters8a7d2d52001-01-16 07:10:57 +0000992 print len(failed), "items had failures:"
993 failed.sort()
994 for thing, (f, t) in failed:
995 print " %3d of %3d in %s" % (f, t, thing)
996 if verbose:
997 print totalt, "tests in", len(self.name2ft), "items."
998 print totalt - totalf, "passed and", totalf, "failed."
999 if totalf:
1000 print "***Test Failed***", totalf, "failures."
1001 elif verbose:
1002 print "Test passed."
1003 return totalf, totalt
1004
1005 def merge(self, other):
1006 """
1007 other -> merge in test results from the other Tester instance.
1008
1009 If self and other both have a test result for something
1010 with the same name, the (#failures, #tests) results are
1011 summed, and a warning is printed to stdout.
1012
1013 >>> from doctest import Tester
1014 >>> t1 = Tester(globs={}, verbose=0)
1015 >>> t1.runstring('''
1016 ... >>> x = 12
1017 ... >>> print x
1018 ... 12
1019 ... ''', "t1example")
1020 (0, 2)
1021 >>>
1022 >>> t2 = Tester(globs={}, verbose=0)
1023 >>> t2.runstring('''
1024 ... >>> x = 13
1025 ... >>> print x
1026 ... 13
1027 ... ''', "t2example")
1028 (0, 2)
1029 >>> common = ">>> assert 1 + 2 == 3\\n"
1030 >>> t1.runstring(common, "common")
1031 (0, 1)
1032 >>> t2.runstring(common, "common")
1033 (0, 1)
1034 >>> t1.merge(t2)
1035 *** Tester.merge: 'common' in both testers; summing outcomes.
1036 >>> t1.summarize(1)
1037 3 items passed all tests:
1038 2 tests in common
1039 2 tests in t1example
1040 2 tests in t2example
1041 6 tests in 3 items.
1042 6 passed and 0 failed.
1043 Test passed.
1044 (0, 6)
1045 >>>
1046 """
1047
1048 d = self.name2ft
1049 for name, (f, t) in other.name2ft.items():
Raymond Hettinger54f02222002-06-01 14:18:47 +00001050 if name in d:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001051 print "*** Tester.merge: '" + name + "' in both" \
1052 " testers; summing outcomes."
1053 f2, t2 = d[name]
1054 f = f + f2
1055 t = t + t2
1056 d[name] = f, t
1057
1058 def __record_outcome(self, name, f, t):
Raymond Hettinger54f02222002-06-01 14:18:47 +00001059 if name in self.name2ft:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001060 print "*** Warning: '" + name + "' was tested before;", \
1061 "summing outcomes."
1062 f2, t2 = self.name2ft[name]
1063 f = f + f2
1064 t = t + t2
1065 self.name2ft[name] = f, t
1066
1067 def __runone(self, target, name):
1068 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +00001069 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001070 prefix, base = name[:i], name[i+1:]
1071 else:
1072 prefix, base = "", base
1073 if self.isprivate(prefix, base):
1074 return 0, 0
1075 return self.rundoc(target, name)
1076
1077master = None
1078
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001079def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +00001080 report=True, optionflags=0):
1081 """m=None, name=None, globs=None, verbose=None, isprivate=None,
1082 report=True, optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +00001083
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001084 Test examples in docstrings in functions and classes reachable
1085 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001086 with m.__doc__. Unless isprivate is specified, private names
1087 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001088
1089 Also test examples reachable from dict m.__test__ if it exists and is
1090 not None. m.__dict__ maps names to functions, classes and strings;
1091 function and class docstrings are tested even if the name is private;
1092 strings are tested directly, as if they were docstrings.
1093
1094 Return (#failures, #tests).
1095
1096 See doctest.__doc__ for an overview.
1097
1098 Optional keyword arg "name" gives the name of the module; by default
1099 use m.__name__.
1100
1101 Optional keyword arg "globs" gives a dict to be used as the globals
1102 when executing examples; by default, use m.__dict__. A copy of this
1103 dict is actually used for each docstring, so that each docstring's
1104 examples start with a clean slate.
1105
1106 Optional keyword arg "verbose" prints lots of stuff if true, prints
1107 only failures if false; by default, it's true iff "-v" is in sys.argv.
1108
1109 Optional keyword arg "isprivate" specifies a function used to
1110 determine whether a name is private. The default function is
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001111 treat all functions as public. Optionally, "isprivate" can be
1112 set to doctest.is_private to skip over functions marked as private
1113 using the underscore naming convention; see its docs for details.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001114
1115 Optional keyword arg "report" prints a summary at the end when true,
1116 else prints nothing at the end. In verbose mode, the summary is
1117 detailed, else very brief (in fact, empty if all tests passed).
1118
Tim Peters6ebe61f2003-06-27 20:48:05 +00001119 Optional keyword arg "optionflags" or's together module constants,
1120 and defaults to 0. This is new in 2.3. Possible values:
1121
1122 DONT_ACCEPT_TRUE_FOR_1
1123 By default, if an expected output block contains just "1",
1124 an actual output block containing just "True" is considered
1125 to be a match, and similarly for "0" versus "False". When
1126 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1127 is allowed.
1128
Tim Peters8a7d2d52001-01-16 07:10:57 +00001129 Advanced tomfoolery: testmod runs methods of a local instance of
1130 class doctest.Tester, then merges the results into (or creates)
1131 global Tester instance doctest.master. Methods of doctest.master
1132 can be called directly too, if you want to do something unusual.
1133 Passing report=0 to testmod is especially useful then, to delay
1134 displaying a summary. Invoke doctest.master.summarize(verbose)
1135 when you're done fiddling.
1136 """
1137
1138 global master
1139
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001140 if m is None:
1141 import sys
1142 # DWA - m will still be None if this wasn't invoked from the command
1143 # line, in which case the following TypeError is about as good an error
1144 # as we should expect
1145 m = sys.modules.get('__main__')
1146
Tim Peters7402f792001-10-02 03:53:41 +00001147 if not _ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001148 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001149 if name is None:
1150 name = m.__name__
Tim Peters6ebe61f2003-06-27 20:48:05 +00001151 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
1152 optionflags=optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001153 failures, tries = tester.rundoc(m, name)
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001154 f, t = tester.rundict(m.__dict__, name, m)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001155 failures += f
1156 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001157 if hasattr(m, "__test__"):
1158 testdict = m.__test__
1159 if testdict:
1160 if not hasattr(testdict, "items"):
1161 raise TypeError("testmod: module.__test__ must support "
Walter Dörwald70a6b492004-02-12 17:35:32 +00001162 ".items(); %r" % (testdict,))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001163 f, t = tester.run__test__(testdict, name + ".__test__")
Tim Peters6ebe61f2003-06-27 20:48:05 +00001164 failures += f
1165 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001166 if report:
1167 tester.summarize()
1168 if master is None:
1169 master = tester
1170 else:
1171 master.merge(tester)
1172 return failures, tries
1173
Tim Petersdb3756d2003-06-29 05:30:48 +00001174###########################################################################
1175# Various doctest extensions, to make using doctest with unittest
1176# easier, and to help debugging when a doctest goes wrong. Original
1177# code by Jim Fulton.
1178
1179# Utilities.
1180
1181# If module is None, return the calling module (the module that called
1182# the routine that called _normalize_module -- this normally won't be
1183# doctest!). If module is a string, it should be the (possibly dotted)
1184# name of a module, and the (rightmost) module object is returned. Else
1185# module is returned untouched; the intent appears to be that module is
1186# already a module object in this case (although this isn't checked).
1187
1188def _normalize_module(module):
1189 import sys
1190
1191 if module is None:
1192 # Get our caller's caller's module.
1193 module = sys._getframe(2).f_globals['__name__']
1194 module = sys.modules[module]
1195
Raymond Hettinger7a70ea42003-09-17 05:50:59 +00001196 elif isinstance(module, basestring):
Tim Petersdb3756d2003-06-29 05:30:48 +00001197 # The ["*"] at the end is a mostly meaningless incantation with
1198 # a crucial property: if, e.g., module is 'a.b.c', it convinces
1199 # __import__ to return c instead of a.
1200 module = __import__(module, globals(), locals(), ["*"])
1201
1202 return module
1203
1204# tests is a list of (testname, docstring, filename, lineno) tuples.
1205# If object has a __doc__ attr, and the __doc__ attr looks like it
1206# contains a doctest (specifically, if it contains an instance of '>>>'),
1207# then tuple
1208# prefix + name, object.__doc__, filename, lineno
1209# is appended to tests. Else tests is left alone.
1210# There is no return value.
1211
1212def _get_doctest(name, object, tests, prefix, filename='', lineno=''):
1213 doc = getattr(object, '__doc__', '')
1214 if isinstance(doc, basestring) and '>>>' in doc:
1215 tests.append((prefix + name, doc, filename, lineno))
1216
1217# tests is a list of (testname, docstring, filename, lineno) tuples.
1218# docstrings containing doctests are appended to tests (if any are found).
1219# items is a dict, like a module or class dict, mapping strings to objects.
1220# mdict is the global dict of a "home" module -- only objects belonging
1221# to this module are searched for docstrings. module is the module to
1222# which mdict belongs.
1223# prefix is a string to be prepended to an object's name when adding a
1224# tuple to tests.
1225# The objects (values) in items are examined (recursively), and doctests
1226# belonging to functions and classes in the home module are appended to
1227# tests.
1228# minlineno is a gimmick to try to guess the file-relative line number
1229# at which a doctest probably begins.
1230
1231def _extract_doctests(items, module, mdict, tests, prefix, minlineno=0):
1232
1233 for name, object in items:
1234 # Only interested in named objects.
1235 if not hasattr(object, '__name__'):
1236 continue
1237
1238 elif hasattr(object, 'func_globals'):
1239 # Looks like a function.
1240 if object.func_globals is not mdict:
1241 # Non-local function.
1242 continue
1243 code = getattr(object, 'func_code', None)
1244 filename = getattr(code, 'co_filename', '')
1245 lineno = getattr(code, 'co_firstlineno', -1) + 1
1246 if minlineno:
1247 minlineno = min(lineno, minlineno)
1248 else:
1249 minlineno = lineno
1250 _get_doctest(name, object, tests, prefix, filename, lineno)
1251
1252 elif hasattr(object, "__module__"):
1253 # Maybe a class-like thing, in which case we care.
1254 if object.__module__ != module.__name__:
1255 # Not the same module.
1256 continue
1257 if not (hasattr(object, '__dict__')
1258 and hasattr(object, '__bases__')):
1259 # Not a class.
1260 continue
1261
1262 lineno = _extract_doctests(object.__dict__.items(),
1263 module,
1264 mdict,
1265 tests,
1266 prefix + name + ".")
1267 # XXX "-3" is unclear.
1268 _get_doctest(name, object, tests, prefix,
1269 lineno="%s (or above)" % (lineno - 3))
1270
1271 return minlineno
1272
1273# Find all the doctests belonging to the module object.
1274# Return a list of
1275# (testname, docstring, filename, lineno)
1276# tuples.
1277
1278def _find_tests(module, prefix=None):
1279 if prefix is None:
1280 prefix = module.__name__
1281 mdict = module.__dict__
1282 tests = []
1283 # Get the module-level doctest (if any).
1284 _get_doctest(prefix, module, tests, '', lineno="1 (or above)")
1285 # Recursively search the module __dict__ for doctests.
1286 if prefix:
1287 prefix += "."
1288 _extract_doctests(mdict.items(), module, mdict, tests, prefix)
1289 return tests
1290
Jim Fultona643b652004-07-14 19:06:50 +00001291###############################################################################
1292# unitest support
Tim Petersdb3756d2003-06-29 05:30:48 +00001293
Jim Fultona643b652004-07-14 19:06:50 +00001294from StringIO import StringIO
1295import os
1296import sys
1297import tempfile
1298import unittest
Tim Petersdb3756d2003-06-29 05:30:48 +00001299
Jim Fultona643b652004-07-14 19:06:50 +00001300class DocTestTestCase(unittest.TestCase):
1301 """A test case that wraps a test function.
Tim Petersdb3756d2003-06-29 05:30:48 +00001302
Jim Fultona643b652004-07-14 19:06:50 +00001303 This is useful for slipping pre-existing test functions into the
1304 PyUnit framework. Optionally, set-up and tidy-up functions can be
1305 supplied. As with TestCase, the tidy-up ('tearDown') function will
1306 always be called if the set-up ('setUp') function ran successfully.
Tim Petersdb3756d2003-06-29 05:30:48 +00001307 """
1308
Jim Fultona643b652004-07-14 19:06:50 +00001309 def __init__(self, tester, name, doc, filename, lineno,
1310 setUp=None, tearDown=None):
1311 unittest.TestCase.__init__(self)
1312 (self.__tester, self.__name, self.__doc,
1313 self.__filename, self.__lineno,
1314 self.__setUp, self.__tearDown
1315 ) = tester, name, doc, filename, lineno, setUp, tearDown
Tim Petersdb3756d2003-06-29 05:30:48 +00001316
Jim Fultona643b652004-07-14 19:06:50 +00001317 def setUp(self):
1318 if self.__setUp is not None:
1319 self.__setUp()
1320
1321 def tearDown(self):
1322 if self.__tearDown is not None:
1323 self.__tearDown()
1324
1325 def runTest(self):
1326 old = sys.stdout
1327 new = StringIO()
1328 try:
1329 sys.stdout = new
1330 failures, tries = self.__tester.runstring(self.__doc, self.__name)
1331 finally:
1332 sys.stdout = old
1333
1334 if failures:
1335 lname = '.'.join(self.__name.split('.')[-1:])
1336 lineno = self.__lineno or "0 (don't know line no)"
1337 raise self.failureException(
1338 'Failed doctest test for %s\n'
1339 ' File "%s", line %s, in %s\n\n%s'
1340 % (self.__name, self.__filename, lineno, lname, new.getvalue())
1341 )
1342
1343 def id(self):
1344 return self.__name
1345
1346 def __repr__(self):
1347 name = self.__name.split('.')
1348 return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
1349
1350 __str__ = __repr__
1351
1352 def shortDescription(self):
1353 return "Doctest: " + self.__name
1354
1355
1356def DocTestSuite(module=None,
1357 setUp=lambda: None,
1358 tearDown=lambda: None,
1359 ):
1360 """Convert doctest tests for a mudule to a unittest test suite
1361
1362 This tests convers each documentation string in a module that
1363 contains doctest tests to a unittest test case. If any of the
1364 tests in a doc string fail, then the test case fails. An error is
1365 raised showing the name of the file containing the test and a
1366 (sometimes approximate) line number.
1367
1368 A module argument provides the module to be tested. The argument
1369 can be either a module or a module name.
1370
1371 If no argument is given, the calling module is used.
1372
1373 """
1374 module = _normalizeModule(module)
1375 tests = _findTests(module)
1376
Tim Petersdb3756d2003-06-29 05:30:48 +00001377 if not tests:
1378 raise ValueError(module, "has no tests")
1379
1380 tests.sort()
1381 suite = unittest.TestSuite()
1382 tester = Tester(module)
1383 for name, doc, filename, lineno in tests:
1384 if not filename:
1385 filename = module.__file__
1386 if filename.endswith(".pyc"):
1387 filename = filename[:-1]
1388 elif filename.endswith(".pyo"):
1389 filename = filename[:-1]
Jim Fultona643b652004-07-14 19:06:50 +00001390
1391 suite.addTest(DocTestTestCase(
1392 tester, name, doc, filename, lineno,
1393 setUp, tearDown))
1394
Tim Petersdb3756d2003-06-29 05:30:48 +00001395 return suite
1396
Jim Fultona643b652004-07-14 19:06:50 +00001397def _normalizeModule(module):
1398 # Normalize a module
1399 if module is None:
1400 # Test the calling module
1401 module = sys._getframe(2).f_globals['__name__']
1402 module = sys.modules[module]
1403
1404 elif isinstance(module, (str, unicode)):
1405 module = __import__(module, globals(), locals(), ["*"])
1406
1407 return module
1408
1409def _doc(name, object, tests, prefix, filename='', lineno=''):
1410 doc = getattr(object, '__doc__', '')
1411 if doc and doc.find('>>>') >= 0:
1412 tests.append((prefix+name, doc, filename, lineno))
1413
1414
1415def _findTests(module, prefix=None):
1416 if prefix is None:
1417 prefix = module.__name__
1418 dict = module.__dict__
1419 tests = []
1420 _doc(prefix, module, tests, '',
1421 lineno="1 (or below)")
1422 prefix = prefix and (prefix + ".")
1423 _find(dict.items(), module, dict, tests, prefix)
1424 return tests
1425
1426def _find(items, module, dict, tests, prefix, minlineno=0):
1427 for name, object in items:
1428
1429 # Only interested in named objects
1430 if not hasattr(object, '__name__'):
1431 continue
1432
1433 if hasattr(object, 'func_globals'):
1434 # Looks like a func
1435 if object.func_globals is not dict:
1436 # Non-local func
1437 continue
1438 code = getattr(object, 'func_code', None)
1439 filename = getattr(code, 'co_filename', '')
1440 lineno = getattr(code, 'co_firstlineno', -1) + 1
1441 if minlineno:
1442 minlineno = min(lineno, minlineno)
1443 else:
1444 minlineno = lineno
1445 _doc(name, object, tests, prefix, filename, lineno)
1446
1447 elif hasattr(object, "__module__"):
1448 # Maybe a class-like things. In which case, we care
1449 if object.__module__ != module.__name__:
1450 continue # not the same module
1451 if not (hasattr(object, '__dict__')
1452 and hasattr(object, '__bases__')):
1453 continue # not a class
1454
1455 lineno = _find(object.__dict__.items(), module, dict, tests,
1456 prefix+name+".")
1457
1458 _doc(name, object, tests, prefix,
1459 lineno="%s (or above)" % (lineno-3))
1460
1461 return minlineno
1462
1463# end unitest support
1464###############################################################################
1465
1466###############################################################################
1467# debugger
Tim Petersdb3756d2003-06-29 05:30:48 +00001468
1469def _expect(expect):
Jim Fultona643b652004-07-14 19:06:50 +00001470 # Return the expected output, if any
Tim Petersdb3756d2003-06-29 05:30:48 +00001471 if expect:
1472 expect = "\n# ".join(expect.split("\n"))
1473 expect = "\n# Expect:\n# %s" % expect
1474 return expect
1475
1476def testsource(module, name):
Jim Fultona643b652004-07-14 19:06:50 +00001477 """Extract the test sources from a doctest test docstring as a script
Tim Petersdb3756d2003-06-29 05:30:48 +00001478
1479 Provide the module (or dotted name of the module) containing the
Jim Fultona643b652004-07-14 19:06:50 +00001480 test to be debugged and the name (within the module) of the object
1481 with the doc string with tests to be debugged.
Tim Petersdb3756d2003-06-29 05:30:48 +00001482
Tim Petersdb3756d2003-06-29 05:30:48 +00001483 """
Jim Fultona643b652004-07-14 19:06:50 +00001484 module = _normalizeModule(module)
1485 tests = _findTests(module, "")
1486 test = [doc for (tname, doc, f, l) in tests if tname == name]
Tim Petersdb3756d2003-06-29 05:30:48 +00001487 if not test:
1488 raise ValueError(name, "not found in tests")
1489 test = test[0]
Jim Fultona643b652004-07-14 19:06:50 +00001490 # XXX we rely on an internal doctest function:
1491 examples = _extract_examples(test)
1492 testsrc = '\n'.join([
1493 "%s%s" % (source, _expect(expect))
1494 for (source, expect, lineno) in examples
1495 ])
1496 return testsrc
Tim Petersdb3756d2003-06-29 05:30:48 +00001497
Jim Fultona643b652004-07-14 19:06:50 +00001498def debug_src(src, pm=False, globs=None):
1499 """Debug a single doctest test doc string
Tim Petersdb3756d2003-06-29 05:30:48 +00001500
Jim Fultona643b652004-07-14 19:06:50 +00001501 The string is provided directly
Tim Petersdb3756d2003-06-29 05:30:48 +00001502 """
Jim Fultona643b652004-07-14 19:06:50 +00001503 # XXX we rely on an internal doctest function:
1504 examples = _extract_examples(src)
1505 src = '\n'.join([
1506 "%s%s" % (source, _expect(expect))
1507 for (source, expect, lineno) in examples
1508 ])
1509 debug_script(src, pm, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00001510
Jim Fultona643b652004-07-14 19:06:50 +00001511def debug_script(src, pm=False, globs=None):
1512 "Debug a test script"
Tim Petersdb3756d2003-06-29 05:30:48 +00001513 import pdb
Tim Petersdb3756d2003-06-29 05:30:48 +00001514
Tim Petersdb3756d2003-06-29 05:30:48 +00001515 srcfilename = tempfile.mktemp("doctestdebug.py")
Jim Fultona643b652004-07-14 19:06:50 +00001516 open(srcfilename, 'w').write(src)
1517 if globs:
1518 globs = globs.copy()
1519 else:
1520 globs = {}
Tim Petersdb3756d2003-06-29 05:30:48 +00001521
Tim Petersdb3756d2003-06-29 05:30:48 +00001522 try:
Jim Fultona643b652004-07-14 19:06:50 +00001523 if pm:
1524 try:
1525 execfile(srcfilename, globs, globs)
1526 except:
1527 print sys.exc_info()[1]
1528 pdb.post_mortem(sys.exc_info()[2])
1529 else:
1530 # Note that %r is vital here. '%s' instead can, e.g., cause
1531 # backslashes to get treated as metacharacters on Windows.
1532 pdb.run("execfile(%r)" % srcfilename, globs, globs)
Tim Petersdb3756d2003-06-29 05:30:48 +00001533 finally:
1534 os.remove(srcfilename)
1535
Jim Fultona643b652004-07-14 19:06:50 +00001536def debug(module, name, pm=False):
1537 """Debug a single doctest test doc string
1538
1539 Provide the module (or dotted name of the module) containing the
1540 test to be debugged and the name (within the module) of the object
1541 with the doc string with tests to be debugged.
1542
1543 """
1544 module = _normalizeModule(module)
1545 testsrc = testsource(module, name)
1546 debug_script(testsrc, pm, module.__dict__)
1547
1548# end debugger
1549###############################################################################
Tim Petersdb3756d2003-06-29 05:30:48 +00001550
1551
Tim Peters8a7d2d52001-01-16 07:10:57 +00001552class _TestClass:
1553 """
1554 A pointless class, for sanity-checking of docstring testing.
1555
1556 Methods:
1557 square()
1558 get()
1559
1560 >>> _TestClass(13).get() + _TestClass(-12).get()
1561 1
1562 >>> hex(_TestClass(13).square().get())
1563 '0xa9'
1564 """
1565
1566 def __init__(self, val):
1567 """val -> _TestClass object with associated value val.
1568
1569 >>> t = _TestClass(123)
1570 >>> print t.get()
1571 123
1572 """
1573
1574 self.val = val
1575
1576 def square(self):
1577 """square() -> square TestClass's associated value
1578
1579 >>> _TestClass(13).square().get()
1580 169
1581 """
1582
1583 self.val = self.val ** 2
1584 return self
1585
1586 def get(self):
1587 """get() -> return TestClass's associated value.
1588
1589 >>> x = _TestClass(-42)
1590 >>> print x.get()
1591 -42
1592 """
1593
1594 return self.val
1595
1596__test__ = {"_TestClass": _TestClass,
1597 "string": r"""
1598 Example of a string object, searched as-is.
1599 >>> x = 1; y = 2
1600 >>> x + y, x * y
1601 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001602 """,
1603 "bool-int equivalence": r"""
1604 In 2.2, boolean expressions displayed
1605 0 or 1. By default, we still accept
1606 them. This can be disabled by passing
1607 DONT_ACCEPT_TRUE_FOR_1 to the new
1608 optionflags argument.
1609 >>> 4 == 4
1610 1
1611 >>> 4 == 4
1612 True
1613 >>> 4 > 4
1614 0
1615 >>> 4 > 4
1616 False
1617 """,
Tim Peters8a7d2d52001-01-16 07:10:57 +00001618 }
1619
1620def _test():
1621 import doctest
1622 return doctest.testmod(doctest)
1623
1624if __name__ == "__main__":
1625 _test()