blob: 50206846457260809b49e89da7a7ab5e151bd13e [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8a7d2d52001-01-16 07:10:57 +00002# Released to the public domain 16-Jan-2001,
3# by Tim Peters (tim.one@home.com).
4
5# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
6
7"""Module doctest -- a framework for running examples in docstrings.
8
9NORMAL USAGE
10
11In normal use, end each module M with:
12
13def _test():
14 import doctest, M # replace M with your module's name
15 return doctest.testmod(M) # ditto
16
17if __name__ == "__main__":
18 _test()
19
20Then running the module as a script will cause the examples in the
21docstrings to get executed and verified:
22
23python M.py
24
25This won't display anything unless an example fails, in which case the
26failing example(s) and the cause(s) of the failure(s) are printed to stdout
27(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
28line of output is "Test failed.".
29
30Run it with the -v switch instead:
31
32python M.py -v
33
34and a detailed report of all examples tried is printed to stdout, along
35with assorted summaries at the end.
36
37You can force verbose mode by passing "verbose=1" to testmod, or prohibit
38it by passing "verbose=0". In either of those cases, sys.argv is not
39examined by testmod.
40
41In any case, testmod returns a 2-tuple of ints (f, t), where f is the
42number of docstring examples that failed and t is the total number of
43docstring examples attempted.
44
45
46WHICH DOCSTRINGS ARE EXAMINED?
47
48+ M.__doc__.
49
50+ f.__doc__ for all functions f in M.__dict__.values(), except those
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
203+ If you continue a line via backslashing in an interactive session, or for
204 any other reason use a backslash, you need to double the backslash in the
205 docstring version. This is simply because you're in a string, and so the
206 backslash must be escaped for it to survive intact. Like:
207
208>>> if "yes" == \\
209... "y" + \\
210... "es": # in the source code you'll see the doubled backslashes
211... print 'yes'
212yes
213
214The starting column doesn't matter:
215
216>>> assert "Easy!"
217 >>> import math
218 >>> math.floor(1.9)
219 1.0
220
221and as many leading whitespace characters are stripped from the expected
222output as appeared in the initial ">>>" line that triggered it.
223
224If you execute this very file, the examples above will be found and
225executed, leading to this output in verbose mode:
226
227Running doctest.__doc__
Tim Peters60e23f42001-02-14 00:43:21 +0000228Trying: [1, 2, 3].remove(42)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000229Expecting:
Tim Petersea4f9312001-02-13 20:54:42 +0000230Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000231 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000232ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000233ok
234Trying: x = 12
235Expecting: nothing
236ok
237Trying: x
238Expecting: 12
239ok
240Trying:
241if x == 13:
242 print "yes"
243else:
244 print "no"
245 print "NO"
246 print "NO!!!"
247Expecting:
248no
249NO
250NO!!!
251ok
252... and a bunch more like that, with this summary at the end:
253
2545 items had no tests:
255 doctest.Tester.__init__
256 doctest.Tester.run__test__
257 doctest.Tester.summarize
258 doctest.run_docstring_examples
259 doctest.testmod
26012 items passed all tests:
261 8 tests in doctest
262 6 tests in doctest.Tester
263 10 tests in doctest.Tester.merge
Tim Peters17111f32001-10-03 04:08:26 +0000264 14 tests in doctest.Tester.rundict
Tim Peters8a7d2d52001-01-16 07:10:57 +0000265 3 tests in doctest.Tester.rundoc
266 3 tests in doctest.Tester.runstring
267 2 tests in doctest.__test__._TestClass
268 2 tests in doctest.__test__._TestClass.__init__
269 2 tests in doctest.__test__._TestClass.get
270 1 tests in doctest.__test__._TestClass.square
271 2 tests in doctest.__test__.string
272 7 tests in doctest.is_private
Tim Peters17111f32001-10-03 04:08:26 +000027360 tests in 17 items.
27460 passed and 0 failed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000275Test passed.
276"""
277
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000278__all__ = [
279 'testmod',
280 'run_docstring_examples',
281 'is_private',
282 'Tester',
Tim Petersdb3756d2003-06-29 05:30:48 +0000283 'DocTestTestFailure',
284 'DocTestSuite',
285 'testsource',
286 'debug',
Raymond Hettingercc39a132003-07-11 22:36:52 +0000287 'master',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000288]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000289
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000290import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000291
Tim Peters8a7d2d52001-01-16 07:10:57 +0000292import re
293PS1 = ">>>"
294PS2 = "..."
295_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
296_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
297_isEmpty = re.compile(r"\s*$").match
298_isComment = re.compile(r"\s*#").match
299del re
300
Tim Peters7402f792001-10-02 03:53:41 +0000301from types import StringTypes as _StringTypes
302
303from inspect import isclass as _isclass
304from inspect import isfunction as _isfunction
Raymond Hettinger5f8b0b12003-09-02 02:09:05 +0000305from inspect import ismethod as _ismethod
Tim Peters7402f792001-10-02 03:53:41 +0000306from inspect import ismodule as _ismodule
Tim Peters17111f32001-10-03 04:08:26 +0000307from inspect import classify_class_attrs as _classify_class_attrs
Tim Peters7402f792001-10-02 03:53:41 +0000308
Tim Peters6ebe61f2003-06-27 20:48:05 +0000309# Option constants.
310DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
311
Tim Peters8a7d2d52001-01-16 07:10:57 +0000312# Extract interactive examples from a string. Return a list of triples,
313# (source, outcome, lineno). "source" is the source code, and ends
314# with a newline iff the source spans more than one line. "outcome" is
315# the expected output if any, else an empty string. When not empty,
316# outcome always ends with a newline. "lineno" is the line number,
317# 0-based wrt the start of the string, of the first source line.
318
319def _extract_examples(s):
320 isPS1, isPS2 = _isPS1, _isPS2
321 isEmpty, isComment = _isEmpty, _isComment
322 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000323 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000324 i, n = 0, len(lines)
325 while i < n:
326 line = lines[i]
327 i = i + 1
328 m = isPS1(line)
329 if m is None:
330 continue
331 j = m.end(0) # beyond the prompt
332 if isEmpty(line, j) or isComment(line, j):
333 # a bare prompt or comment -- not interesting
334 continue
335 lineno = i - 1
336 if line[j] != " ":
Walter Dörwald70a6b492004-02-12 17:35:32 +0000337 raise ValueError("line %r of docstring lacks blank after %s: %s" %
338 (lineno, PS1, line))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000339 j = j + 1
340 blanks = m.group(1)
341 nblanks = len(blanks)
342 # suck up this and following PS2 lines
343 source = []
344 while 1:
345 source.append(line[j:])
346 line = lines[i]
347 m = isPS2(line)
348 if m:
349 if m.group(1) != blanks:
350 raise ValueError("inconsistent leading whitespace "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000351 "in line %r of docstring: %s" % (i, line))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000352 i = i + 1
353 else:
354 break
355 if len(source) == 1:
356 source = source[0]
357 else:
358 # get rid of useless null line from trailing empty "..."
359 if source[-1] == "":
360 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000361 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000362 # suck up response
363 if isPS1(line) or isEmpty(line):
364 expect = ""
365 else:
366 expect = []
367 while 1:
368 if line[:nblanks] != blanks:
369 raise ValueError("inconsistent leading whitespace "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000370 "in line %r of docstring: %s" % (i, line))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000371 expect.append(line[nblanks:])
372 i = i + 1
373 line = lines[i]
374 if isPS1(line) or isEmpty(line):
375 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000376 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000377 examples.append( (source, expect, lineno) )
378 return examples
379
380# Capture stdout when running examples.
381
382class _SpoofOut:
383 def __init__(self):
384 self.clear()
385 def write(self, s):
386 self.buf.append(s)
387 def get(self):
Tim Petersf9bb4962001-02-14 06:35:35 +0000388 guts = "".join(self.buf)
389 # If anything at all was written, make sure there's a trailing
390 # newline. There's no way for the expected output to indicate
391 # that a trailing newline is missing.
392 if guts and not guts.endswith("\n"):
393 guts = guts + "\n"
Tim Petersc77db342001-10-23 02:21:52 +0000394 # Prevent softspace from screwing up the next test case, in
395 # case they used print with a trailing comma in an example.
396 if hasattr(self, "softspace"):
397 del self.softspace
Tim Petersf9bb4962001-02-14 06:35:35 +0000398 return guts
Tim Peters8a7d2d52001-01-16 07:10:57 +0000399 def clear(self):
400 self.buf = []
Tim Petersc77db342001-10-23 02:21:52 +0000401 if hasattr(self, "softspace"):
402 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000403 def flush(self):
404 # JPython calls flush
405 pass
406
407# Display some tag-and-msg pairs nicely, keeping the tag and its msg
408# on the same line when that makes sense.
409
410def _tag_out(printer, *tag_msg_pairs):
411 for tag, msg in tag_msg_pairs:
412 printer(tag + ":")
413 msg_has_nl = msg[-1:] == "\n"
414 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000415 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000416 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
417 printer(" ")
418 else:
419 printer("\n")
420 printer(msg)
421 if not msg_has_nl:
422 printer("\n")
423
424# Run list of examples, in context globs. "out" can be used to display
425# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
426# that captures the examples' std output. Return (#failures, #tries).
427
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000428def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000429 compileflags, optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000430 import sys, traceback
431 OK, BOOM, FAIL = range(3)
432 NADA = "nothing"
433 stderr = _SpoofOut()
434 failures = 0
435 for source, want, lineno in examples:
436 if verbose:
437 _tag_out(out, ("Trying", source),
438 ("Expecting", want or NADA))
439 fakeout.clear()
440 try:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000441 exec compile(source, "<string>", "single",
442 compileflags, 1) in globs
Tim Peters8a7d2d52001-01-16 07:10:57 +0000443 got = fakeout.get()
444 state = OK
Tim Petersbcc2c122002-03-20 19:32:03 +0000445 except KeyboardInterrupt:
446 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000447 except:
448 # See whether the exception was expected.
Tim Petersea4f9312001-02-13 20:54:42 +0000449 if want.find("Traceback (innermost last):\n") == 0 or \
450 want.find("Traceback (most recent call last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000451 # Only compare exception type and value - the rest of
452 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000453 want = want.split('\n')[-2] + '\n'
Tim Peters77f2d502001-06-24 18:59:01 +0000454 exc_type, exc_val = sys.exc_info()[:2]
Tim Peters08bba952001-06-24 06:46:58 +0000455 got = traceback.format_exception_only(exc_type, exc_val)[-1]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000456 state = OK
457 else:
458 # unexpected exception
459 stderr.clear()
460 traceback.print_exc(file=stderr)
461 state = BOOM
462
463 if state == OK:
Tim Peters6ebe61f2003-06-27 20:48:05 +0000464 if (got == want or
465 (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and
466 (got, want) in (("True\n", "1\n"), ("False\n", "0\n"))
467 )
468 ):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000469 if verbose:
470 out("ok\n")
471 continue
472 state = FAIL
473
474 assert state in (FAIL, BOOM)
475 failures = failures + 1
476 out("*" * 65 + "\n")
477 _tag_out(out, ("Failure in example", source))
Walter Dörwald70a6b492004-02-12 17:35:32 +0000478 out("from line #%r of %s\n" % (lineno, name))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000479 if state == FAIL:
480 _tag_out(out, ("Expected", want or NADA), ("Got", got))
481 else:
482 assert state == BOOM
483 _tag_out(out, ("Exception raised", stderr.get()))
484
485 return failures, len(examples)
486
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000487# Get the future-flags associated with the future features that have been
488# imported into globs.
489
490def _extract_future_flags(globs):
491 flags = 0
492 for fname in __future__.all_feature_names:
493 feature = globs.get(fname, None)
494 if feature is getattr(__future__, fname):
495 flags |= feature.compiler_flag
496 return flags
497
Tim Petersd4ad59e2001-06-24 20:02:47 +0000498# Run list of examples, in a shallow copy of context (dict) globs.
499# Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000500
Tim Peters6ebe61f2003-06-27 20:48:05 +0000501def _run_examples(examples, globs, verbose, name, compileflags,
502 optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000503 import sys
504 saveout = sys.stdout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000505 globs = globs.copy()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000506 try:
507 sys.stdout = fakeout = _SpoofOut()
508 x = _run_examples_inner(saveout.write, fakeout, examples,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000509 globs, verbose, name, compileflags,
510 optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000511 finally:
512 sys.stdout = saveout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000513 # While Python gc can clean up most cycles on its own, it doesn't
514 # chase frame objects. This is especially irksome when running
515 # generator tests that raise exceptions, because a named generator-
516 # iterator gets an entry in globs, and the generator-iterator
517 # object's frame's traceback info points back to globs. This is
Tim Petersfee69d02001-06-24 20:24:16 +0000518 # easy to break just by clearing the namespace. This can also
519 # help to break other kinds of cycles, and even for cycles that
520 # gc can break itself it's better to break them ASAP.
Tim Petersd4ad59e2001-06-24 20:02:47 +0000521 globs.clear()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000522 return x
523
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000524def run_docstring_examples(f, globs, verbose=0, name="NoName",
Tim Peters6ebe61f2003-06-27 20:48:05 +0000525 compileflags=None, optionflags=0):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000526 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
527
Tim Petersd4ad59e2001-06-24 20:02:47 +0000528 Use (a shallow copy of) dict globs as the globals for execution.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000529 Return (#failures, #tries).
530
531 If optional arg verbose is true, print stuff even if there are no
532 failures.
533 Use string name in failure msgs.
534 """
535
536 try:
537 doc = f.__doc__
538 if not doc:
539 # docstring empty or None
540 return 0, 0
541 # just in case CT invents a doc object that has to be forced
542 # to look like a string <0.9 wink>
543 doc = str(doc)
Tim Petersbcc2c122002-03-20 19:32:03 +0000544 except KeyboardInterrupt:
545 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000546 except:
547 return 0, 0
548
549 e = _extract_examples(doc)
550 if not e:
551 return 0, 0
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000552 if compileflags is None:
553 compileflags = _extract_future_flags(globs)
Tim Peters6ebe61f2003-06-27 20:48:05 +0000554 return _run_examples(e, globs, verbose, name, compileflags, optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000555
556def is_private(prefix, base):
557 """prefix, base -> true iff name prefix + "." + base is "private".
558
559 Prefix may be an empty string, and base does not contain a period.
560 Prefix is ignored (although functions you write conforming to this
561 protocol may make use of it).
562 Return true iff base begins with an (at least one) underscore, but
563 does not both begin and end with (at least) two underscores.
564
565 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000566 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000567 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000568 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000569 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000570 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000571 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000572 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000573 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000574 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000575 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000576 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000577 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000578 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000579 """
580
581 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
582
Tim Peters7402f792001-10-02 03:53:41 +0000583# Determine if a class of function was defined in the given module.
584
585def _from_module(module, object):
586 if _isfunction(object):
587 return module.__dict__ is object.func_globals
588 if _isclass(object):
589 return module.__name__ == object.__module__
590 raise ValueError("object must be a class or function")
591
Tim Peters8a7d2d52001-01-16 07:10:57 +0000592class Tester:
593 """Class Tester -- runs docstring examples and accumulates stats.
594
595In normal use, function doctest.testmod() hides all this from you,
596so use that if you can. Create your own instances of Tester to do
597fancier things.
598
599Methods:
600 runstring(s, name)
601 Search string s for examples to run; use name for logging.
602 Return (#failures, #tries).
603
604 rundoc(object, name=None)
605 Search object.__doc__ for examples to run; use name (or
606 object.__name__) for logging. Return (#failures, #tries).
607
Tim Peters7402f792001-10-02 03:53:41 +0000608 rundict(d, name, module=None)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000609 Search for examples in docstrings in all of d.values(); use name
Tim Peters7402f792001-10-02 03:53:41 +0000610 for logging. Exclude functions and classes not defined in module
611 if specified. Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000612
613 run__test__(d, name)
614 Treat dict d like module.__test__. Return (#failures, #tries).
615
616 summarize(verbose=None)
617 Display summary of testing results, to stdout. Return
618 (#failures, #tries).
619
620 merge(other)
621 Merge in the test results from Tester instance "other".
622
623>>> from doctest import Tester
624>>> t = Tester(globs={'x': 42}, verbose=0)
625>>> t.runstring(r'''
626... >>> x = x * 2
627... >>> print x
628... 42
629... ''', 'XYZ')
630*****************************************************************
631Failure in example: print x
632from line #2 of XYZ
633Expected: 42
634Got: 84
635(1, 2)
636>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
637(0, 2)
638>>> t.summarize()
Guido van Rossum261d91a2001-03-18 17:05:58 +0000639*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006401 items had failures:
641 1 of 2 in XYZ
642***Test Failed*** 1 failures.
643(1, 4)
644>>> t.summarize(verbose=1)
6451 items passed all tests:
646 2 tests in example2
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
6504 tests in 2 items.
6513 passed and 1 failed.
652***Test Failed*** 1 failures.
653(1, 4)
654>>>
655"""
656
657 def __init__(self, mod=None, globs=None, verbose=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000658 isprivate=None, optionflags=0):
659 """mod=None, globs=None, verbose=None, isprivate=None,
660optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000661
662See doctest.__doc__ for an overview.
663
664Optional keyword arg "mod" is a module, whose globals are used for
665executing examples. If not specified, globs must be specified.
666
667Optional keyword arg "globs" gives a dict to be used as the globals
668when executing examples; if not specified, use the globals from
669module mod.
670
671In either case, a copy of the dict is used for each docstring
672examined.
673
674Optional keyword arg "verbose" prints lots of stuff if true, only
675failures if false; by default, it's true iff "-v" is in sys.argv.
676
677Optional keyword arg "isprivate" specifies a function used to determine
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000678whether a name is private. The default function is to assume that
679no functions are private. The "isprivate" arg may be set to
680doctest.is_private in order to skip over functions marked as private
681using an underscore naming convention; see its docs for details.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000682
683See doctest.testmod docs for the meaning of optionflags.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000684"""
685
686 if mod is None and globs is None:
687 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters7402f792001-10-02 03:53:41 +0000688 if mod is not None and not _ismodule(mod):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000689 raise TypeError("Tester.__init__: mod must be a module; %r" % (mod,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000690 if globs is None:
691 globs = mod.__dict__
692 self.globs = globs
693
694 if verbose is None:
695 import sys
696 verbose = "-v" in sys.argv
697 self.verbose = verbose
698
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000699 # By default, assume that nothing is private
Tim Peters8a7d2d52001-01-16 07:10:57 +0000700 if isprivate is None:
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000701 isprivate = lambda prefix, base: 0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000702 self.isprivate = isprivate
703
Tim Peters6ebe61f2003-06-27 20:48:05 +0000704 self.optionflags = optionflags
705
Tim Peters8a7d2d52001-01-16 07:10:57 +0000706 self.name2ft = {} # map name to (#failures, #trials) pair
707
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000708 self.compileflags = _extract_future_flags(globs)
709
Tim Peters8a7d2d52001-01-16 07:10:57 +0000710 def runstring(self, s, name):
711 """
712 s, name -> search string s for examples to run, logging as name.
713
714 Use string name as the key for logging the outcome.
715 Return (#failures, #examples).
716
717 >>> t = Tester(globs={}, verbose=1)
718 >>> test = r'''
719 ... # just an example
720 ... >>> x = 1 + 2
721 ... >>> x
722 ... 3
723 ... '''
724 >>> t.runstring(test, "Example")
725 Running string Example
726 Trying: x = 1 + 2
727 Expecting: nothing
728 ok
729 Trying: x
730 Expecting: 3
731 ok
732 0 of 2 examples failed in string Example
733 (0, 2)
734 """
735
736 if self.verbose:
737 print "Running string", name
738 f = t = 0
739 e = _extract_examples(s)
740 if e:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000741 f, t = _run_examples(e, self.globs, self.verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000742 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000743 if self.verbose:
744 print f, "of", t, "examples failed in string", name
745 self.__record_outcome(name, f, t)
746 return f, t
747
748 def rundoc(self, object, name=None):
749 """
750 object, name=None -> search object.__doc__ for examples to run.
751
752 Use optional string name as the key for logging the outcome;
753 by default use object.__name__.
754 Return (#failures, #examples).
755 If object is a class object, search recursively for method
756 docstrings too.
757 object.__doc__ is examined regardless of name, but if object is
758 a class, whether private names reached from object are searched
759 depends on the constructor's "isprivate" argument.
760
761 >>> t = Tester(globs={}, verbose=0)
762 >>> def _f():
763 ... '''Trivial docstring example.
764 ... >>> assert 2 == 2
765 ... '''
766 ... return 32
767 ...
768 >>> t.rundoc(_f) # expect 0 failures in 1 example
769 (0, 1)
770 """
771
772 if name is None:
773 try:
774 name = object.__name__
775 except AttributeError:
776 raise ValueError("Tester.rundoc: name must be given "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000777 "when object.__name__ doesn't exist; %r" % (object,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000778 if self.verbose:
779 print "Running", name + ".__doc__"
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000780 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
Tim Peters275abbd2003-06-29 03:11:20 +0000781 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000782 if self.verbose:
783 print f, "of", t, "examples failed in", name + ".__doc__"
784 self.__record_outcome(name, f, t)
Tim Peters7402f792001-10-02 03:53:41 +0000785 if _isclass(object):
Tim Peters17111f32001-10-03 04:08:26 +0000786 # In 2.2, class and static methods complicate life. Build
787 # a dict "that works", by hook or by crook.
788 d = {}
789 for tag, kind, homecls, value in _classify_class_attrs(object):
790
791 if homecls is not object:
792 # Only look at names defined immediately by the class.
793 continue
794
795 elif self.isprivate(name, tag):
796 continue
797
798 elif kind == "method":
799 # value is already a function
800 d[tag] = value
801
802 elif kind == "static method":
803 # value isn't a function, but getattr reveals one
804 d[tag] = getattr(object, tag)
805
806 elif kind == "class method":
807 # Hmm. A classmethod object doesn't seem to reveal
808 # enough. But getattr turns it into a bound method,
809 # and from there .im_func retrieves the underlying
810 # function.
811 d[tag] = getattr(object, tag).im_func
812
813 elif kind == "property":
814 # The methods implementing the property have their
815 # own docstrings -- but the property may have one too.
816 if value.__doc__ is not None:
817 d[tag] = str(value.__doc__)
818
819 elif kind == "data":
820 # Grab nested classes.
821 if _isclass(value):
822 d[tag] = value
823
824 else:
825 raise ValueError("teach doctest about %r" % kind)
826
827 f2, t2 = self.run__test__(d, name)
828 f += f2
829 t += t2
830
Tim Peters8a7d2d52001-01-16 07:10:57 +0000831 return f, t
832
Tim Peters7402f792001-10-02 03:53:41 +0000833 def rundict(self, d, name, module=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000834 """
Tim Peters7402f792001-10-02 03:53:41 +0000835 d, name, module=None -> search for docstring examples in d.values().
Tim Peters8a7d2d52001-01-16 07:10:57 +0000836
837 For k, v in d.items() such that v is a function or class,
838 do self.rundoc(v, name + "." + k). Whether this includes
839 objects with private names depends on the constructor's
Tim Peters7402f792001-10-02 03:53:41 +0000840 "isprivate" argument. If module is specified, functions and
841 classes that are not defined in module are excluded.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000842 Return aggregate (#failures, #examples).
843
Tim Peters7402f792001-10-02 03:53:41 +0000844 Build and populate two modules with sample functions to test that
845 exclusion of external functions and classes works.
846
847 >>> import new
848 >>> m1 = new.module('_m1')
849 >>> m2 = new.module('_m2')
850 >>> test_data = \"""
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000851 ... def _f():
Tim Peters7402f792001-10-02 03:53:41 +0000852 ... '''>>> assert 1 == 1
853 ... '''
854 ... def g():
Tim Peters8a7d2d52001-01-16 07:10:57 +0000855 ... '''>>> assert 2 != 1
856 ... '''
Tim Peters7402f792001-10-02 03:53:41 +0000857 ... class H:
858 ... '''>>> assert 2 > 1
859 ... '''
860 ... def bar(self):
861 ... '''>>> assert 1 < 2
862 ... '''
863 ... \"""
864 >>> exec test_data in m1.__dict__
865 >>> exec test_data in m2.__dict__
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000866 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tim Peters7402f792001-10-02 03:53:41 +0000867
868 Tests that objects outside m1 are excluded:
869
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000870 >>> t = Tester(globs={}, verbose=0, isprivate=is_private)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000871 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000872 (0, 3)
873
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000874 Again, but with the default isprivate function allowing _f:
Tim Peters7402f792001-10-02 03:53:41 +0000875
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000876 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000877 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000878 (0, 4)
879
880 And once more, not excluding stuff outside m1:
881
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000882 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000883 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Tim Peters7402f792001-10-02 03:53:41 +0000884 (0, 8)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000885
886 The exclusion of objects from outside the designated module is
887 meant to be invoked automagically by testmod.
888
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000889 >>> testmod(m1, isprivate=is_private)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000890 (0, 3)
891
Tim Peters8a7d2d52001-01-16 07:10:57 +0000892 """
893
894 if not hasattr(d, "items"):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000895 raise TypeError("Tester.rundict: d must support .items(); %r" % (d,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000896 f = t = 0
Tim Peters24a41912001-03-21 23:07:59 +0000897 # Run the tests by alpha order of names, for consistency in
898 # verbose-mode output.
899 names = d.keys()
900 names.sort()
901 for thisname in names:
902 value = d[thisname]
Tim Peters7402f792001-10-02 03:53:41 +0000903 if _isfunction(value) or _isclass(value):
904 if module and not _from_module(module, value):
905 continue
Tim Peters8a7d2d52001-01-16 07:10:57 +0000906 f2, t2 = self.__runone(value, name + "." + thisname)
907 f = f + f2
908 t = t + t2
909 return f, t
910
911 def run__test__(self, d, name):
912 """d, name -> Treat dict d like module.__test__.
913
914 Return (#failures, #tries).
915 See testmod.__doc__ for details.
916 """
917
918 failures = tries = 0
919 prefix = name + "."
920 savepvt = self.isprivate
921 try:
922 self.isprivate = lambda *args: 0
Tim Peters24a41912001-03-21 23:07:59 +0000923 # Run the tests by alpha order of names, for consistency in
924 # verbose-mode output.
925 keys = d.keys()
926 keys.sort()
927 for k in keys:
928 v = d[k]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000929 thisname = prefix + k
Tim Peters7402f792001-10-02 03:53:41 +0000930 if type(v) in _StringTypes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000931 f, t = self.runstring(v, thisname)
Raymond Hettinger5f8b0b12003-09-02 02:09:05 +0000932 elif _isfunction(v) or _isclass(v) or _ismethod(v):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000933 f, t = self.rundoc(v, thisname)
934 else:
935 raise TypeError("Tester.run__test__: values in "
Raymond Hettinger5f8b0b12003-09-02 02:09:05 +0000936 "dict must be strings, functions, methods, "
Walter Dörwald70a6b492004-02-12 17:35:32 +0000937 "or classes; %r" % (v,))
Tim Peters8a7d2d52001-01-16 07:10:57 +0000938 failures = failures + f
939 tries = tries + t
940 finally:
941 self.isprivate = savepvt
942 return failures, tries
943
944 def summarize(self, verbose=None):
945 """
946 verbose=None -> summarize results, return (#failures, #tests).
947
948 Print summary of test results to stdout.
949 Optional arg 'verbose' controls how wordy this is. By
950 default, use the verbose setting established by the
951 constructor.
952 """
953
954 if verbose is None:
955 verbose = self.verbose
956 notests = []
957 passed = []
958 failed = []
959 totalt = totalf = 0
960 for x in self.name2ft.items():
961 name, (f, t) = x
962 assert f <= t
963 totalt = totalt + t
964 totalf = totalf + f
965 if t == 0:
966 notests.append(name)
967 elif f == 0:
968 passed.append( (name, t) )
969 else:
970 failed.append(x)
971 if verbose:
972 if notests:
973 print len(notests), "items had no tests:"
974 notests.sort()
975 for thing in notests:
976 print " ", thing
977 if passed:
978 print len(passed), "items passed all tests:"
979 passed.sort()
980 for thing, count in passed:
981 print " %3d tests in %s" % (count, thing)
982 if failed:
Guido van Rossumaf00a462001-03-18 16:58:44 +0000983 print "*" * 65
Tim Peters8a7d2d52001-01-16 07:10:57 +0000984 print len(failed), "items had failures:"
985 failed.sort()
986 for thing, (f, t) in failed:
987 print " %3d of %3d in %s" % (f, t, thing)
988 if verbose:
989 print totalt, "tests in", len(self.name2ft), "items."
990 print totalt - totalf, "passed and", totalf, "failed."
991 if totalf:
992 print "***Test Failed***", totalf, "failures."
993 elif verbose:
994 print "Test passed."
995 return totalf, totalt
996
997 def merge(self, other):
998 """
999 other -> merge in test results from the other Tester instance.
1000
1001 If self and other both have a test result for something
1002 with the same name, the (#failures, #tests) results are
1003 summed, and a warning is printed to stdout.
1004
1005 >>> from doctest import Tester
1006 >>> t1 = Tester(globs={}, verbose=0)
1007 >>> t1.runstring('''
1008 ... >>> x = 12
1009 ... >>> print x
1010 ... 12
1011 ... ''', "t1example")
1012 (0, 2)
1013 >>>
1014 >>> t2 = Tester(globs={}, verbose=0)
1015 >>> t2.runstring('''
1016 ... >>> x = 13
1017 ... >>> print x
1018 ... 13
1019 ... ''', "t2example")
1020 (0, 2)
1021 >>> common = ">>> assert 1 + 2 == 3\\n"
1022 >>> t1.runstring(common, "common")
1023 (0, 1)
1024 >>> t2.runstring(common, "common")
1025 (0, 1)
1026 >>> t1.merge(t2)
1027 *** Tester.merge: 'common' in both testers; summing outcomes.
1028 >>> t1.summarize(1)
1029 3 items passed all tests:
1030 2 tests in common
1031 2 tests in t1example
1032 2 tests in t2example
1033 6 tests in 3 items.
1034 6 passed and 0 failed.
1035 Test passed.
1036 (0, 6)
1037 >>>
1038 """
1039
1040 d = self.name2ft
1041 for name, (f, t) in other.name2ft.items():
Raymond Hettinger54f02222002-06-01 14:18:47 +00001042 if name in d:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001043 print "*** Tester.merge: '" + name + "' in both" \
1044 " testers; summing outcomes."
1045 f2, t2 = d[name]
1046 f = f + f2
1047 t = t + t2
1048 d[name] = f, t
1049
1050 def __record_outcome(self, name, f, t):
Raymond Hettinger54f02222002-06-01 14:18:47 +00001051 if name in self.name2ft:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001052 print "*** Warning: '" + name + "' was tested before;", \
1053 "summing outcomes."
1054 f2, t2 = self.name2ft[name]
1055 f = f + f2
1056 t = t + t2
1057 self.name2ft[name] = f, t
1058
1059 def __runone(self, target, name):
1060 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +00001061 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001062 prefix, base = name[:i], name[i+1:]
1063 else:
1064 prefix, base = "", base
1065 if self.isprivate(prefix, base):
1066 return 0, 0
1067 return self.rundoc(target, name)
1068
1069master = None
1070
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001071def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +00001072 report=True, optionflags=0):
1073 """m=None, name=None, globs=None, verbose=None, isprivate=None,
1074 report=True, optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +00001075
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001076 Test examples in docstrings in functions and classes reachable
1077 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001078 with m.__doc__. Unless isprivate is specified, private names
1079 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001080
1081 Also test examples reachable from dict m.__test__ if it exists and is
1082 not None. m.__dict__ maps names to functions, classes and strings;
1083 function and class docstrings are tested even if the name is private;
1084 strings are tested directly, as if they were docstrings.
1085
1086 Return (#failures, #tests).
1087
1088 See doctest.__doc__ for an overview.
1089
1090 Optional keyword arg "name" gives the name of the module; by default
1091 use m.__name__.
1092
1093 Optional keyword arg "globs" gives a dict to be used as the globals
1094 when executing examples; by default, use m.__dict__. A copy of this
1095 dict is actually used for each docstring, so that each docstring's
1096 examples start with a clean slate.
1097
1098 Optional keyword arg "verbose" prints lots of stuff if true, prints
1099 only failures if false; by default, it's true iff "-v" is in sys.argv.
1100
1101 Optional keyword arg "isprivate" specifies a function used to
1102 determine whether a name is private. The default function is
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001103 treat all functions as public. Optionally, "isprivate" can be
1104 set to doctest.is_private to skip over functions marked as private
1105 using the underscore naming convention; see its docs for details.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001106
1107 Optional keyword arg "report" prints a summary at the end when true,
1108 else prints nothing at the end. In verbose mode, the summary is
1109 detailed, else very brief (in fact, empty if all tests passed).
1110
Tim Peters6ebe61f2003-06-27 20:48:05 +00001111 Optional keyword arg "optionflags" or's together module constants,
1112 and defaults to 0. This is new in 2.3. Possible values:
1113
1114 DONT_ACCEPT_TRUE_FOR_1
1115 By default, if an expected output block contains just "1",
1116 an actual output block containing just "True" is considered
1117 to be a match, and similarly for "0" versus "False". When
1118 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1119 is allowed.
1120
Tim Peters8a7d2d52001-01-16 07:10:57 +00001121 Advanced tomfoolery: testmod runs methods of a local instance of
1122 class doctest.Tester, then merges the results into (or creates)
1123 global Tester instance doctest.master. Methods of doctest.master
1124 can be called directly too, if you want to do something unusual.
1125 Passing report=0 to testmod is especially useful then, to delay
1126 displaying a summary. Invoke doctest.master.summarize(verbose)
1127 when you're done fiddling.
1128 """
1129
1130 global master
1131
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001132 if m is None:
1133 import sys
1134 # DWA - m will still be None if this wasn't invoked from the command
1135 # line, in which case the following TypeError is about as good an error
1136 # as we should expect
1137 m = sys.modules.get('__main__')
1138
Tim Peters7402f792001-10-02 03:53:41 +00001139 if not _ismodule(m):
Walter Dörwald70a6b492004-02-12 17:35:32 +00001140 raise TypeError("testmod: module required; %r" % (m,))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001141 if name is None:
1142 name = m.__name__
Tim Peters6ebe61f2003-06-27 20:48:05 +00001143 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
1144 optionflags=optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001145 failures, tries = tester.rundoc(m, name)
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001146 f, t = tester.rundict(m.__dict__, name, m)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001147 failures += f
1148 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001149 if hasattr(m, "__test__"):
1150 testdict = m.__test__
1151 if testdict:
1152 if not hasattr(testdict, "items"):
1153 raise TypeError("testmod: module.__test__ must support "
Walter Dörwald70a6b492004-02-12 17:35:32 +00001154 ".items(); %r" % (testdict,))
Tim Peters8a7d2d52001-01-16 07:10:57 +00001155 f, t = tester.run__test__(testdict, name + ".__test__")
Tim Peters6ebe61f2003-06-27 20:48:05 +00001156 failures += f
1157 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001158 if report:
1159 tester.summarize()
1160 if master is None:
1161 master = tester
1162 else:
1163 master.merge(tester)
1164 return failures, tries
1165
Tim Petersdb3756d2003-06-29 05:30:48 +00001166###########################################################################
1167# Various doctest extensions, to make using doctest with unittest
1168# easier, and to help debugging when a doctest goes wrong. Original
1169# code by Jim Fulton.
1170
1171# Utilities.
1172
1173# If module is None, return the calling module (the module that called
1174# the routine that called _normalize_module -- this normally won't be
1175# doctest!). If module is a string, it should be the (possibly dotted)
1176# name of a module, and the (rightmost) module object is returned. Else
1177# module is returned untouched; the intent appears to be that module is
1178# already a module object in this case (although this isn't checked).
1179
1180def _normalize_module(module):
1181 import sys
1182
1183 if module is None:
1184 # Get our caller's caller's module.
1185 module = sys._getframe(2).f_globals['__name__']
1186 module = sys.modules[module]
1187
Raymond Hettinger7a70ea42003-09-17 05:50:59 +00001188 elif isinstance(module, basestring):
Tim Petersdb3756d2003-06-29 05:30:48 +00001189 # The ["*"] at the end is a mostly meaningless incantation with
1190 # a crucial property: if, e.g., module is 'a.b.c', it convinces
1191 # __import__ to return c instead of a.
1192 module = __import__(module, globals(), locals(), ["*"])
1193
1194 return module
1195
1196# tests is a list of (testname, docstring, filename, lineno) tuples.
1197# If object has a __doc__ attr, and the __doc__ attr looks like it
1198# contains a doctest (specifically, if it contains an instance of '>>>'),
1199# then tuple
1200# prefix + name, object.__doc__, filename, lineno
1201# is appended to tests. Else tests is left alone.
1202# There is no return value.
1203
1204def _get_doctest(name, object, tests, prefix, filename='', lineno=''):
1205 doc = getattr(object, '__doc__', '')
1206 if isinstance(doc, basestring) and '>>>' in doc:
1207 tests.append((prefix + name, doc, filename, lineno))
1208
1209# tests is a list of (testname, docstring, filename, lineno) tuples.
1210# docstrings containing doctests are appended to tests (if any are found).
1211# items is a dict, like a module or class dict, mapping strings to objects.
1212# mdict is the global dict of a "home" module -- only objects belonging
1213# to this module are searched for docstrings. module is the module to
1214# which mdict belongs.
1215# prefix is a string to be prepended to an object's name when adding a
1216# tuple to tests.
1217# The objects (values) in items are examined (recursively), and doctests
1218# belonging to functions and classes in the home module are appended to
1219# tests.
1220# minlineno is a gimmick to try to guess the file-relative line number
1221# at which a doctest probably begins.
1222
1223def _extract_doctests(items, module, mdict, tests, prefix, minlineno=0):
1224
1225 for name, object in items:
1226 # Only interested in named objects.
1227 if not hasattr(object, '__name__'):
1228 continue
1229
1230 elif hasattr(object, 'func_globals'):
1231 # Looks like a function.
1232 if object.func_globals is not mdict:
1233 # Non-local function.
1234 continue
1235 code = getattr(object, 'func_code', None)
1236 filename = getattr(code, 'co_filename', '')
1237 lineno = getattr(code, 'co_firstlineno', -1) + 1
1238 if minlineno:
1239 minlineno = min(lineno, minlineno)
1240 else:
1241 minlineno = lineno
1242 _get_doctest(name, object, tests, prefix, filename, lineno)
1243
1244 elif hasattr(object, "__module__"):
1245 # Maybe a class-like thing, in which case we care.
1246 if object.__module__ != module.__name__:
1247 # Not the same module.
1248 continue
1249 if not (hasattr(object, '__dict__')
1250 and hasattr(object, '__bases__')):
1251 # Not a class.
1252 continue
1253
1254 lineno = _extract_doctests(object.__dict__.items(),
1255 module,
1256 mdict,
1257 tests,
1258 prefix + name + ".")
1259 # XXX "-3" is unclear.
1260 _get_doctest(name, object, tests, prefix,
1261 lineno="%s (or above)" % (lineno - 3))
1262
1263 return minlineno
1264
1265# Find all the doctests belonging to the module object.
1266# Return a list of
1267# (testname, docstring, filename, lineno)
1268# tuples.
1269
1270def _find_tests(module, prefix=None):
1271 if prefix is None:
1272 prefix = module.__name__
1273 mdict = module.__dict__
1274 tests = []
1275 # Get the module-level doctest (if any).
1276 _get_doctest(prefix, module, tests, '', lineno="1 (or above)")
1277 # Recursively search the module __dict__ for doctests.
1278 if prefix:
1279 prefix += "."
1280 _extract_doctests(mdict.items(), module, mdict, tests, prefix)
1281 return tests
1282
1283# unittest helpers.
1284
1285# A function passed to unittest, for unittest to drive.
1286# tester is doctest Tester instance. doc is the docstring whose
1287# doctests are to be run.
1288
1289def _utest(tester, name, doc, filename, lineno):
1290 import sys
1291 from StringIO import StringIO
1292
1293 old = sys.stdout
1294 sys.stdout = new = StringIO()
1295 try:
1296 failures, tries = tester.runstring(doc, name)
1297 finally:
1298 sys.stdout = old
1299
1300 if failures:
1301 msg = new.getvalue()
1302 lname = '.'.join(name.split('.')[-1:])
1303 if not lineno:
1304 lineno = "0 (don't know line number)"
1305 # Don't change this format! It was designed so that Emacs can
1306 # parse it naturally.
1307 raise DocTestTestFailure('Failed doctest test for %s\n'
1308 ' File "%s", line %s, in %s\n\n%s' %
1309 (name, filename, lineno, lname, msg))
1310
1311class DocTestTestFailure(Exception):
1312 """A doctest test failed"""
1313
1314def DocTestSuite(module=None):
1315 """Convert doctest tests for a module to a unittest TestSuite.
1316
1317 The returned TestSuite is to be run by the unittest framework, and
1318 runs each doctest in the module. If any of the doctests fail,
1319 then the synthesized unit test fails, and an error is raised showing
1320 the name of the file containing the test and a (sometimes approximate)
1321 line number.
1322
1323 The optional module argument provides the module to be tested. It
1324 can be a module object or a (possibly dotted) module name. If not
1325 specified, the module calling DocTestSuite() is used.
1326
1327 Example (although note that unittest supplies many ways to use the
1328 TestSuite returned; see the unittest docs):
1329
1330 import unittest
1331 import doctest
1332 import my_module_with_doctests
1333
1334 suite = doctest.DocTestSuite(my_module_with_doctests)
1335 runner = unittest.TextTestRunner()
1336 runner.run(suite)
1337 """
1338
1339 import unittest
1340
1341 module = _normalize_module(module)
1342 tests = _find_tests(module)
1343 if not tests:
1344 raise ValueError(module, "has no tests")
1345
1346 tests.sort()
1347 suite = unittest.TestSuite()
1348 tester = Tester(module)
1349 for name, doc, filename, lineno in tests:
1350 if not filename:
1351 filename = module.__file__
1352 if filename.endswith(".pyc"):
1353 filename = filename[:-1]
1354 elif filename.endswith(".pyo"):
1355 filename = filename[:-1]
1356 def runit(name=name, doc=doc, filename=filename, lineno=lineno):
1357 _utest(tester, name, doc, filename, lineno)
1358 suite.addTest(unittest.FunctionTestCase(
1359 runit,
1360 description="doctest of " + name))
1361 return suite
1362
1363# Debugging support.
1364
1365def _expect(expect):
1366 # Return the expected output (if any), formatted as a Python
1367 # comment block.
1368 if expect:
1369 expect = "\n# ".join(expect.split("\n"))
1370 expect = "\n# Expect:\n# %s" % expect
1371 return expect
1372
1373def testsource(module, name):
1374 """Extract the doctest examples from a docstring.
1375
1376 Provide the module (or dotted name of the module) containing the
1377 tests to be extracted, and the name (within the module) of the object
1378 with the docstring containing the tests to be extracted.
1379
1380 The doctest examples are returned as a string containing Python
1381 code. The expected output blocks in the examples are converted
1382 to Python comments.
1383 """
1384
1385 module = _normalize_module(module)
1386 tests = _find_tests(module, "")
1387 test = [doc for (tname, doc, dummy, dummy) in tests
1388 if tname == name]
1389 if not test:
1390 raise ValueError(name, "not found in tests")
1391 test = test[0]
1392 examples = [source + _expect(expect)
1393 for source, expect, dummy in _extract_examples(test)]
1394 return '\n'.join(examples)
1395
1396def debug(module, name):
1397 """Debug a single docstring containing doctests.
1398
1399 Provide the module (or dotted name of the module) containing the
1400 docstring to be debugged, and the name (within the module) of the
1401 object with the docstring to be debugged.
1402
1403 The doctest examples are extracted (see function testsource()),
1404 and written to a temp file. The Python debugger (pdb) is then
1405 invoked on that file.
1406 """
1407
1408 import os
1409 import pdb
1410 import tempfile
1411
1412 module = _normalize_module(module)
1413 testsrc = testsource(module, name)
1414 srcfilename = tempfile.mktemp("doctestdebug.py")
1415 f = file(srcfilename, 'w')
1416 f.write(testsrc)
1417 f.close()
1418
1419 globs = {}
1420 globs.update(module.__dict__)
1421 try:
1422 # Note that %r is vital here. '%s' instead can, e.g., cause
1423 # backslashes to get treated as metacharacters on Windows.
1424 pdb.run("execfile(%r)" % srcfilename, globs, globs)
1425 finally:
1426 os.remove(srcfilename)
1427
1428
1429
Tim Peters8a7d2d52001-01-16 07:10:57 +00001430class _TestClass:
1431 """
1432 A pointless class, for sanity-checking of docstring testing.
1433
1434 Methods:
1435 square()
1436 get()
1437
1438 >>> _TestClass(13).get() + _TestClass(-12).get()
1439 1
1440 >>> hex(_TestClass(13).square().get())
1441 '0xa9'
1442 """
1443
1444 def __init__(self, val):
1445 """val -> _TestClass object with associated value val.
1446
1447 >>> t = _TestClass(123)
1448 >>> print t.get()
1449 123
1450 """
1451
1452 self.val = val
1453
1454 def square(self):
1455 """square() -> square TestClass's associated value
1456
1457 >>> _TestClass(13).square().get()
1458 169
1459 """
1460
1461 self.val = self.val ** 2
1462 return self
1463
1464 def get(self):
1465 """get() -> return TestClass's associated value.
1466
1467 >>> x = _TestClass(-42)
1468 >>> print x.get()
1469 -42
1470 """
1471
1472 return self.val
1473
1474__test__ = {"_TestClass": _TestClass,
1475 "string": r"""
1476 Example of a string object, searched as-is.
1477 >>> x = 1; y = 2
1478 >>> x + y, x * y
1479 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001480 """,
1481 "bool-int equivalence": r"""
1482 In 2.2, boolean expressions displayed
1483 0 or 1. By default, we still accept
1484 them. This can be disabled by passing
1485 DONT_ACCEPT_TRUE_FOR_1 to the new
1486 optionflags argument.
1487 >>> 4 == 4
1488 1
1489 >>> 4 == 4
1490 True
1491 >>> 4 > 4
1492 0
1493 >>> 4 > 4
1494 False
1495 """,
Tim Peters8a7d2d52001-01-16 07:10:57 +00001496 }
1497
1498def _test():
1499 import doctest
1500 return doctest.testmod(doctest)
1501
1502if __name__ == "__main__":
1503 _test()