blob: 55f15f11378fac8e5cf54ce24aafa0ed32878b09 [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8a7d2d52001-01-16 07:10:57 +00002# Released to the public domain 16-Jan-2001,
3# by Tim Peters (tim.one@home.com).
4
5# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
6
7"""Module doctest -- a framework for running examples in docstrings.
8
9NORMAL USAGE
10
11In normal use, end each module M with:
12
13def _test():
14 import doctest, M # replace M with your module's name
15 return doctest.testmod(M) # ditto
16
17if __name__ == "__main__":
18 _test()
19
20Then running the module as a script will cause the examples in the
21docstrings to get executed and verified:
22
23python M.py
24
25This won't display anything unless an example fails, in which case the
26failing example(s) and the cause(s) of the failure(s) are printed to stdout
27(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
28line of output is "Test failed.".
29
30Run it with the -v switch instead:
31
32python M.py -v
33
34and a detailed report of all examples tried is printed to stdout, along
35with assorted summaries at the end.
36
37You can force verbose mode by passing "verbose=1" to testmod, or prohibit
38it by passing "verbose=0". In either of those cases, sys.argv is not
39examined by testmod.
40
41In any case, testmod returns a 2-tuple of ints (f, t), where f is the
42number of docstring examples that failed and t is the total number of
43docstring examples attempted.
44
45
46WHICH DOCSTRINGS ARE EXAMINED?
47
48+ M.__doc__.
49
50+ f.__doc__ for all functions f in M.__dict__.values(), except those
Tim Peters7402f792001-10-02 03:53:41 +000051 with private names and those defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000052
53+ C.__doc__ for all classes C in M.__dict__.values(), except those with
Tim Peters7402f792001-10-02 03:53:41 +000054 private names and those defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000055
56+ If M.__test__ exists and "is true", it must be a dict, and
57 each entry maps a (string) name to a function object, class object, or
58 string. Function and class object docstrings found from M.__test__
59 are searched even if the name is private, and strings are searched
60 directly as if they were docstrings. In output, a key K in M.__test__
61 appears with name
62 <name of M>.__test__.K
63
64Any classes found are recursively searched similarly, to test docstrings in
65their contained methods and nested classes. Private names reached from M's
66globals are skipped, but all names reached from M.__test__ are searched.
67
68By default, a name is considered to be private if it begins with an
69underscore (like "_my_func") but doesn't both begin and end with (at least)
70two underscores (like "__init__"). You can change the default by passing
71your own "isprivate" function to testmod.
72
73If you want to test docstrings in objects with private names too, stuff
74them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
75own isprivate function to Tester's constructor, or call the rundoc method
76of a Tester instance).
77
Tim Peters8a7d2d52001-01-16 07:10:57 +000078WHAT'S THE EXECUTION CONTEXT?
79
80By default, each time testmod finds a docstring to test, it uses a *copy*
81of M's globals (so that running tests on a module doesn't change the
82module's real globals, and so that one test in M can't leave behind crumbs
83that accidentally allow another test to work). This means examples can
84freely use any names defined at top-level in M. It also means that sloppy
85imports (see above) can cause examples in external docstrings to use
86globals inappropriate for them.
87
88You can force use of your own dict as the execution context by passing
89"globs=your_dict" to testmod instead. Presumably this would be a copy of
90M.__dict__ merged with the globals from other imported modules.
91
92
93WHAT IF I WANT TO TEST A WHOLE PACKAGE?
94
95Piece o' cake, provided the modules do their testing from docstrings.
96Here's the test.py I use for the world's most elaborate Rational/
97floating-base-conversion pkg (which I'll distribute some day):
98
99from Rational import Cvt
100from Rational import Format
101from Rational import machprec
102from Rational import Rat
103from Rational import Round
104from Rational import utils
105
106modules = (Cvt,
107 Format,
108 machprec,
109 Rat,
110 Round,
111 utils)
112
113def _test():
114 import doctest
115 import sys
116 verbose = "-v" in sys.argv
117 for mod in modules:
118 doctest.testmod(mod, verbose=verbose, report=0)
119 doctest.master.summarize()
120
121if __name__ == "__main__":
122 _test()
123
124IOW, it just runs testmod on all the pkg modules. testmod remembers the
125names and outcomes (# of failures, # of tries) for each item it's seen, and
126passing "report=0" prevents it from printing a summary in verbose mode.
127Instead, the summary is delayed until all modules have been tested, and
128then "doctest.master.summarize()" forces the summary at the end.
129
130So this is very nice in practice: each module can be tested individually
131with almost no work beyond writing up docstring examples, and collections
132of modules can be tested too as a unit with no more work than the above.
133
134
135WHAT ABOUT EXCEPTIONS?
136
137No problem, as long as the only output generated by the example is the
138traceback itself. For example:
139
Tim Peters60e23f42001-02-14 00:43:21 +0000140 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +0000141 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000142 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000143 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000144 >>>
145
146Note that only the exception type and value are compared (specifically,
147only the last line in the traceback).
148
149
150ADVANCED USAGE
151
152doctest.testmod() captures the testing policy I find most useful most
153often. You may want other policies.
154
155testmod() actually creates a local instance of class doctest.Tester, runs
156appropriate methods of that class, and merges the results into global
157Tester instance doctest.master.
158
159You can create your own instances of doctest.Tester, and so build your own
160policies, or even run methods of doctest.master directly. See
161doctest.Tester.__doc__ for details.
162
163
164SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
165
166Oh ya. It's easy! In most cases a copy-and-paste of an interactive
167console session works fine -- just make sure the leading whitespace is
168rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
169right, but doctest is not in the business of guessing what you think a tab
170means).
171
172 >>> # comments are ignored
173 >>> x = 12
174 >>> x
175 12
176 >>> if x == 13:
177 ... print "yes"
178 ... else:
179 ... print "no"
180 ... print "NO"
181 ... print "NO!!!"
182 ...
183 no
184 NO
185 NO!!!
186 >>>
187
188Any expected output must immediately follow the final ">>>" or "..." line
189containing the code, and the expected output (if any) extends to the next
190">>>" or all-whitespace line. That's it.
191
192Bummers:
193
194+ Expected output cannot contain an all-whitespace line, since such a line
195 is taken to signal the end of expected output.
196
197+ Output to stdout is captured, but not output to stderr (exception
198 tracebacks are captured via a different means).
199
200+ If you continue a line via backslashing in an interactive session, or for
201 any other reason use a backslash, you need to double the backslash in the
202 docstring version. This is simply because you're in a string, and so the
203 backslash must be escaped for it to survive intact. Like:
204
205>>> if "yes" == \\
206... "y" + \\
207... "es": # in the source code you'll see the doubled backslashes
208... print 'yes'
209yes
210
211The starting column doesn't matter:
212
213>>> assert "Easy!"
214 >>> import math
215 >>> math.floor(1.9)
216 1.0
217
218and as many leading whitespace characters are stripped from the expected
219output as appeared in the initial ">>>" line that triggered it.
220
221If you execute this very file, the examples above will be found and
222executed, leading to this output in verbose mode:
223
224Running doctest.__doc__
Tim Peters60e23f42001-02-14 00:43:21 +0000225Trying: [1, 2, 3].remove(42)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000226Expecting:
Tim Petersea4f9312001-02-13 20:54:42 +0000227Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000228 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000229ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000230ok
231Trying: x = 12
232Expecting: nothing
233ok
234Trying: x
235Expecting: 12
236ok
237Trying:
238if x == 13:
239 print "yes"
240else:
241 print "no"
242 print "NO"
243 print "NO!!!"
244Expecting:
245no
246NO
247NO!!!
248ok
249... and a bunch more like that, with this summary at the end:
250
2515 items had no tests:
252 doctest.Tester.__init__
253 doctest.Tester.run__test__
254 doctest.Tester.summarize
255 doctest.run_docstring_examples
256 doctest.testmod
25712 items passed all tests:
258 8 tests in doctest
259 6 tests in doctest.Tester
260 10 tests in doctest.Tester.merge
Tim Peters17111f32001-10-03 04:08:26 +0000261 14 tests in doctest.Tester.rundict
Tim Peters8a7d2d52001-01-16 07:10:57 +0000262 3 tests in doctest.Tester.rundoc
263 3 tests in doctest.Tester.runstring
264 2 tests in doctest.__test__._TestClass
265 2 tests in doctest.__test__._TestClass.__init__
266 2 tests in doctest.__test__._TestClass.get
267 1 tests in doctest.__test__._TestClass.square
268 2 tests in doctest.__test__.string
269 7 tests in doctest.is_private
Tim Peters17111f32001-10-03 04:08:26 +000027060 tests in 17 items.
27160 passed and 0 failed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000272Test passed.
273"""
274
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000275__all__ = [
276 'testmod',
277 'run_docstring_examples',
278 'is_private',
279 'Tester',
Tim Petersdb3756d2003-06-29 05:30:48 +0000280 'DocTestTestFailure',
281 'DocTestSuite',
282 'testsource',
283 'debug',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000284]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000285
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000286import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000287
Tim Peters8a7d2d52001-01-16 07:10:57 +0000288import re
289PS1 = ">>>"
290PS2 = "..."
291_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
292_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
293_isEmpty = re.compile(r"\s*$").match
294_isComment = re.compile(r"\s*#").match
295del re
296
Tim Peters7402f792001-10-02 03:53:41 +0000297from types import StringTypes as _StringTypes
298
299from inspect import isclass as _isclass
300from inspect import isfunction as _isfunction
301from inspect import ismodule as _ismodule
Tim Peters17111f32001-10-03 04:08:26 +0000302from inspect import classify_class_attrs as _classify_class_attrs
Tim Peters7402f792001-10-02 03:53:41 +0000303
Tim Peters6ebe61f2003-06-27 20:48:05 +0000304# Option constants.
305DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
306
Tim Peters8a7d2d52001-01-16 07:10:57 +0000307# Extract interactive examples from a string. Return a list of triples,
308# (source, outcome, lineno). "source" is the source code, and ends
309# with a newline iff the source spans more than one line. "outcome" is
310# the expected output if any, else an empty string. When not empty,
311# outcome always ends with a newline. "lineno" is the line number,
312# 0-based wrt the start of the string, of the first source line.
313
314def _extract_examples(s):
315 isPS1, isPS2 = _isPS1, _isPS2
316 isEmpty, isComment = _isEmpty, _isComment
317 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000318 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000319 i, n = 0, len(lines)
320 while i < n:
321 line = lines[i]
322 i = i + 1
323 m = isPS1(line)
324 if m is None:
325 continue
326 j = m.end(0) # beyond the prompt
327 if isEmpty(line, j) or isComment(line, j):
328 # a bare prompt or comment -- not interesting
329 continue
330 lineno = i - 1
331 if line[j] != " ":
332 raise ValueError("line " + `lineno` + " of docstring lacks "
333 "blank after " + PS1 + ": " + line)
334 j = j + 1
335 blanks = m.group(1)
336 nblanks = len(blanks)
337 # suck up this and following PS2 lines
338 source = []
339 while 1:
340 source.append(line[j:])
341 line = lines[i]
342 m = isPS2(line)
343 if m:
344 if m.group(1) != blanks:
345 raise ValueError("inconsistent leading whitespace "
346 "in line " + `i` + " of docstring: " + line)
347 i = i + 1
348 else:
349 break
350 if len(source) == 1:
351 source = source[0]
352 else:
353 # get rid of useless null line from trailing empty "..."
354 if source[-1] == "":
355 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000356 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000357 # suck up response
358 if isPS1(line) or isEmpty(line):
359 expect = ""
360 else:
361 expect = []
362 while 1:
363 if line[:nblanks] != blanks:
364 raise ValueError("inconsistent leading whitespace "
365 "in line " + `i` + " of docstring: " + line)
366 expect.append(line[nblanks:])
367 i = i + 1
368 line = lines[i]
369 if isPS1(line) or isEmpty(line):
370 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000371 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000372 examples.append( (source, expect, lineno) )
373 return examples
374
375# Capture stdout when running examples.
376
377class _SpoofOut:
378 def __init__(self):
379 self.clear()
380 def write(self, s):
381 self.buf.append(s)
382 def get(self):
Tim Petersf9bb4962001-02-14 06:35:35 +0000383 guts = "".join(self.buf)
384 # If anything at all was written, make sure there's a trailing
385 # newline. There's no way for the expected output to indicate
386 # that a trailing newline is missing.
387 if guts and not guts.endswith("\n"):
388 guts = guts + "\n"
Tim Petersc77db342001-10-23 02:21:52 +0000389 # Prevent softspace from screwing up the next test case, in
390 # case they used print with a trailing comma in an example.
391 if hasattr(self, "softspace"):
392 del self.softspace
Tim Petersf9bb4962001-02-14 06:35:35 +0000393 return guts
Tim Peters8a7d2d52001-01-16 07:10:57 +0000394 def clear(self):
395 self.buf = []
Tim Petersc77db342001-10-23 02:21:52 +0000396 if hasattr(self, "softspace"):
397 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000398 def flush(self):
399 # JPython calls flush
400 pass
401
402# Display some tag-and-msg pairs nicely, keeping the tag and its msg
403# on the same line when that makes sense.
404
405def _tag_out(printer, *tag_msg_pairs):
406 for tag, msg in tag_msg_pairs:
407 printer(tag + ":")
408 msg_has_nl = msg[-1:] == "\n"
409 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000410 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000411 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
412 printer(" ")
413 else:
414 printer("\n")
415 printer(msg)
416 if not msg_has_nl:
417 printer("\n")
418
419# Run list of examples, in context globs. "out" can be used to display
420# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
421# that captures the examples' std output. Return (#failures, #tries).
422
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000423def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000424 compileflags, optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000425 import sys, traceback
426 OK, BOOM, FAIL = range(3)
427 NADA = "nothing"
428 stderr = _SpoofOut()
429 failures = 0
430 for source, want, lineno in examples:
431 if verbose:
432 _tag_out(out, ("Trying", source),
433 ("Expecting", want or NADA))
434 fakeout.clear()
435 try:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000436 exec compile(source, "<string>", "single",
437 compileflags, 1) in globs
Tim Peters8a7d2d52001-01-16 07:10:57 +0000438 got = fakeout.get()
439 state = OK
Tim Petersbcc2c122002-03-20 19:32:03 +0000440 except KeyboardInterrupt:
441 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000442 except:
443 # See whether the exception was expected.
Tim Petersea4f9312001-02-13 20:54:42 +0000444 if want.find("Traceback (innermost last):\n") == 0 or \
445 want.find("Traceback (most recent call last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000446 # Only compare exception type and value - the rest of
447 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000448 want = want.split('\n')[-2] + '\n'
Tim Peters77f2d502001-06-24 18:59:01 +0000449 exc_type, exc_val = sys.exc_info()[:2]
Tim Peters08bba952001-06-24 06:46:58 +0000450 got = traceback.format_exception_only(exc_type, exc_val)[-1]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000451 state = OK
452 else:
453 # unexpected exception
454 stderr.clear()
455 traceback.print_exc(file=stderr)
456 state = BOOM
457
458 if state == OK:
Tim Peters6ebe61f2003-06-27 20:48:05 +0000459 if (got == want or
460 (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and
461 (got, want) in (("True\n", "1\n"), ("False\n", "0\n"))
462 )
463 ):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000464 if verbose:
465 out("ok\n")
466 continue
467 state = FAIL
468
469 assert state in (FAIL, BOOM)
470 failures = failures + 1
471 out("*" * 65 + "\n")
472 _tag_out(out, ("Failure in example", source))
473 out("from line #" + `lineno` + " of " + name + "\n")
474 if state == FAIL:
475 _tag_out(out, ("Expected", want or NADA), ("Got", got))
476 else:
477 assert state == BOOM
478 _tag_out(out, ("Exception raised", stderr.get()))
479
480 return failures, len(examples)
481
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000482# Get the future-flags associated with the future features that have been
483# imported into globs.
484
485def _extract_future_flags(globs):
486 flags = 0
487 for fname in __future__.all_feature_names:
488 feature = globs.get(fname, None)
489 if feature is getattr(__future__, fname):
490 flags |= feature.compiler_flag
491 return flags
492
Tim Petersd4ad59e2001-06-24 20:02:47 +0000493# Run list of examples, in a shallow copy of context (dict) globs.
494# Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000495
Tim Peters6ebe61f2003-06-27 20:48:05 +0000496def _run_examples(examples, globs, verbose, name, compileflags,
497 optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000498 import sys
499 saveout = sys.stdout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000500 globs = globs.copy()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000501 try:
502 sys.stdout = fakeout = _SpoofOut()
503 x = _run_examples_inner(saveout.write, fakeout, examples,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000504 globs, verbose, name, compileflags,
505 optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000506 finally:
507 sys.stdout = saveout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000508 # While Python gc can clean up most cycles on its own, it doesn't
509 # chase frame objects. This is especially irksome when running
510 # generator tests that raise exceptions, because a named generator-
511 # iterator gets an entry in globs, and the generator-iterator
512 # object's frame's traceback info points back to globs. This is
Tim Petersfee69d02001-06-24 20:24:16 +0000513 # easy to break just by clearing the namespace. This can also
514 # help to break other kinds of cycles, and even for cycles that
515 # gc can break itself it's better to break them ASAP.
Tim Petersd4ad59e2001-06-24 20:02:47 +0000516 globs.clear()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000517 return x
518
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000519def run_docstring_examples(f, globs, verbose=0, name="NoName",
Tim Peters6ebe61f2003-06-27 20:48:05 +0000520 compileflags=None, optionflags=0):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000521 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
522
Tim Petersd4ad59e2001-06-24 20:02:47 +0000523 Use (a shallow copy of) dict globs as the globals for execution.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000524 Return (#failures, #tries).
525
526 If optional arg verbose is true, print stuff even if there are no
527 failures.
528 Use string name in failure msgs.
529 """
530
531 try:
532 doc = f.__doc__
533 if not doc:
534 # docstring empty or None
535 return 0, 0
536 # just in case CT invents a doc object that has to be forced
537 # to look like a string <0.9 wink>
538 doc = str(doc)
Tim Petersbcc2c122002-03-20 19:32:03 +0000539 except KeyboardInterrupt:
540 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000541 except:
542 return 0, 0
543
544 e = _extract_examples(doc)
545 if not e:
546 return 0, 0
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000547 if compileflags is None:
548 compileflags = _extract_future_flags(globs)
Tim Peters6ebe61f2003-06-27 20:48:05 +0000549 return _run_examples(e, globs, verbose, name, compileflags, optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000550
551def is_private(prefix, base):
552 """prefix, base -> true iff name prefix + "." + base is "private".
553
554 Prefix may be an empty string, and base does not contain a period.
555 Prefix is ignored (although functions you write conforming to this
556 protocol may make use of it).
557 Return true iff base begins with an (at least one) underscore, but
558 does not both begin and end with (at least) two underscores.
559
560 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000561 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000562 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000563 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000564 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000565 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000566 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000567 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000568 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000569 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000570 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000571 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000572 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000573 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000574 """
575
576 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
577
Tim Peters7402f792001-10-02 03:53:41 +0000578# Determine if a class of function was defined in the given module.
579
580def _from_module(module, object):
581 if _isfunction(object):
582 return module.__dict__ is object.func_globals
583 if _isclass(object):
584 return module.__name__ == object.__module__
585 raise ValueError("object must be a class or function")
586
Tim Peters8a7d2d52001-01-16 07:10:57 +0000587class Tester:
588 """Class Tester -- runs docstring examples and accumulates stats.
589
590In normal use, function doctest.testmod() hides all this from you,
591so use that if you can. Create your own instances of Tester to do
592fancier things.
593
594Methods:
595 runstring(s, name)
596 Search string s for examples to run; use name for logging.
597 Return (#failures, #tries).
598
599 rundoc(object, name=None)
600 Search object.__doc__ for examples to run; use name (or
601 object.__name__) for logging. Return (#failures, #tries).
602
Tim Peters7402f792001-10-02 03:53:41 +0000603 rundict(d, name, module=None)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000604 Search for examples in docstrings in all of d.values(); use name
Tim Peters7402f792001-10-02 03:53:41 +0000605 for logging. Exclude functions and classes not defined in module
606 if specified. Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000607
608 run__test__(d, name)
609 Treat dict d like module.__test__. Return (#failures, #tries).
610
611 summarize(verbose=None)
612 Display summary of testing results, to stdout. Return
613 (#failures, #tries).
614
615 merge(other)
616 Merge in the test results from Tester instance "other".
617
618>>> from doctest import Tester
619>>> t = Tester(globs={'x': 42}, verbose=0)
620>>> t.runstring(r'''
621... >>> x = x * 2
622... >>> print x
623... 42
624... ''', 'XYZ')
625*****************************************************************
626Failure in example: print x
627from line #2 of XYZ
628Expected: 42
629Got: 84
630(1, 2)
631>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
632(0, 2)
633>>> t.summarize()
Guido van Rossum261d91a2001-03-18 17:05:58 +0000634*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006351 items had failures:
636 1 of 2 in XYZ
637***Test Failed*** 1 failures.
638(1, 4)
639>>> t.summarize(verbose=1)
6401 items passed all tests:
641 2 tests in example2
Guido van Rossum261d91a2001-03-18 17:05:58 +0000642*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006431 items had failures:
644 1 of 2 in XYZ
6454 tests in 2 items.
6463 passed and 1 failed.
647***Test Failed*** 1 failures.
648(1, 4)
649>>>
650"""
651
652 def __init__(self, mod=None, globs=None, verbose=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000653 isprivate=None, optionflags=0):
654 """mod=None, globs=None, verbose=None, isprivate=None,
655optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000656
657See doctest.__doc__ for an overview.
658
659Optional keyword arg "mod" is a module, whose globals are used for
660executing examples. If not specified, globs must be specified.
661
662Optional keyword arg "globs" gives a dict to be used as the globals
663when executing examples; if not specified, use the globals from
664module mod.
665
666In either case, a copy of the dict is used for each docstring
667examined.
668
669Optional keyword arg "verbose" prints lots of stuff if true, only
670failures if false; by default, it's true iff "-v" is in sys.argv.
671
672Optional keyword arg "isprivate" specifies a function used to determine
673whether a name is private. The default function is doctest.is_private;
674see its docs for details.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000675
676See doctest.testmod docs for the meaning of optionflags.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000677"""
678
679 if mod is None and globs is None:
680 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters7402f792001-10-02 03:53:41 +0000681 if mod is not None and not _ismodule(mod):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000682 raise TypeError("Tester.__init__: mod must be a module; " +
683 `mod`)
684 if globs is None:
685 globs = mod.__dict__
686 self.globs = globs
687
688 if verbose is None:
689 import sys
690 verbose = "-v" in sys.argv
691 self.verbose = verbose
692
693 if isprivate is None:
694 isprivate = is_private
695 self.isprivate = isprivate
696
Tim Peters6ebe61f2003-06-27 20:48:05 +0000697 self.optionflags = optionflags
698
Tim Peters8a7d2d52001-01-16 07:10:57 +0000699 self.name2ft = {} # map name to (#failures, #trials) pair
700
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000701 self.compileflags = _extract_future_flags(globs)
702
Tim Peters8a7d2d52001-01-16 07:10:57 +0000703 def runstring(self, s, name):
704 """
705 s, name -> search string s for examples to run, logging as name.
706
707 Use string name as the key for logging the outcome.
708 Return (#failures, #examples).
709
710 >>> t = Tester(globs={}, verbose=1)
711 >>> test = r'''
712 ... # just an example
713 ... >>> x = 1 + 2
714 ... >>> x
715 ... 3
716 ... '''
717 >>> t.runstring(test, "Example")
718 Running string Example
719 Trying: x = 1 + 2
720 Expecting: nothing
721 ok
722 Trying: x
723 Expecting: 3
724 ok
725 0 of 2 examples failed in string Example
726 (0, 2)
727 """
728
729 if self.verbose:
730 print "Running string", name
731 f = t = 0
732 e = _extract_examples(s)
733 if e:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000734 f, t = _run_examples(e, self.globs, self.verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000735 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000736 if self.verbose:
737 print f, "of", t, "examples failed in string", name
738 self.__record_outcome(name, f, t)
739 return f, t
740
741 def rundoc(self, object, name=None):
742 """
743 object, name=None -> search object.__doc__ for examples to run.
744
745 Use optional string name as the key for logging the outcome;
746 by default use object.__name__.
747 Return (#failures, #examples).
748 If object is a class object, search recursively for method
749 docstrings too.
750 object.__doc__ is examined regardless of name, but if object is
751 a class, whether private names reached from object are searched
752 depends on the constructor's "isprivate" argument.
753
754 >>> t = Tester(globs={}, verbose=0)
755 >>> def _f():
756 ... '''Trivial docstring example.
757 ... >>> assert 2 == 2
758 ... '''
759 ... return 32
760 ...
761 >>> t.rundoc(_f) # expect 0 failures in 1 example
762 (0, 1)
763 """
764
765 if name is None:
766 try:
767 name = object.__name__
768 except AttributeError:
769 raise ValueError("Tester.rundoc: name must be given "
770 "when object.__name__ doesn't exist; " + `object`)
771 if self.verbose:
772 print "Running", name + ".__doc__"
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000773 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
Tim Peters275abbd2003-06-29 03:11:20 +0000774 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000775 if self.verbose:
776 print f, "of", t, "examples failed in", name + ".__doc__"
777 self.__record_outcome(name, f, t)
Tim Peters7402f792001-10-02 03:53:41 +0000778 if _isclass(object):
Tim Peters17111f32001-10-03 04:08:26 +0000779 # In 2.2, class and static methods complicate life. Build
780 # a dict "that works", by hook or by crook.
781 d = {}
782 for tag, kind, homecls, value in _classify_class_attrs(object):
783
784 if homecls is not object:
785 # Only look at names defined immediately by the class.
786 continue
787
788 elif self.isprivate(name, tag):
789 continue
790
791 elif kind == "method":
792 # value is already a function
793 d[tag] = value
794
795 elif kind == "static method":
796 # value isn't a function, but getattr reveals one
797 d[tag] = getattr(object, tag)
798
799 elif kind == "class method":
800 # Hmm. A classmethod object doesn't seem to reveal
801 # enough. But getattr turns it into a bound method,
802 # and from there .im_func retrieves the underlying
803 # function.
804 d[tag] = getattr(object, tag).im_func
805
806 elif kind == "property":
807 # The methods implementing the property have their
808 # own docstrings -- but the property may have one too.
809 if value.__doc__ is not None:
810 d[tag] = str(value.__doc__)
811
812 elif kind == "data":
813 # Grab nested classes.
814 if _isclass(value):
815 d[tag] = value
816
817 else:
818 raise ValueError("teach doctest about %r" % kind)
819
820 f2, t2 = self.run__test__(d, name)
821 f += f2
822 t += t2
823
Tim Peters8a7d2d52001-01-16 07:10:57 +0000824 return f, t
825
Tim Peters7402f792001-10-02 03:53:41 +0000826 def rundict(self, d, name, module=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000827 """
Tim Peters7402f792001-10-02 03:53:41 +0000828 d, name, module=None -> search for docstring examples in d.values().
Tim Peters8a7d2d52001-01-16 07:10:57 +0000829
830 For k, v in d.items() such that v is a function or class,
831 do self.rundoc(v, name + "." + k). Whether this includes
832 objects with private names depends on the constructor's
Tim Peters7402f792001-10-02 03:53:41 +0000833 "isprivate" argument. If module is specified, functions and
834 classes that are not defined in module are excluded.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000835 Return aggregate (#failures, #examples).
836
Tim Peters7402f792001-10-02 03:53:41 +0000837 Build and populate two modules with sample functions to test that
838 exclusion of external functions and classes works.
839
840 >>> import new
841 >>> m1 = new.module('_m1')
842 >>> m2 = new.module('_m2')
843 >>> test_data = \"""
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000844 ... def _f():
Tim Peters7402f792001-10-02 03:53:41 +0000845 ... '''>>> assert 1 == 1
846 ... '''
847 ... def g():
Tim Peters8a7d2d52001-01-16 07:10:57 +0000848 ... '''>>> assert 2 != 1
849 ... '''
Tim Peters7402f792001-10-02 03:53:41 +0000850 ... class H:
851 ... '''>>> assert 2 > 1
852 ... '''
853 ... def bar(self):
854 ... '''>>> assert 1 < 2
855 ... '''
856 ... \"""
857 >>> exec test_data in m1.__dict__
858 >>> exec test_data in m2.__dict__
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000859 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tim Peters7402f792001-10-02 03:53:41 +0000860
861 Tests that objects outside m1 are excluded:
862
Tim Peters8a7d2d52001-01-16 07:10:57 +0000863 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000864 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000865 (0, 3)
866
867 Again, but with a custom isprivate function allowing _f:
868
Tim Peters8a7d2d52001-01-16 07:10:57 +0000869 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000870 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000871 (0, 4)
872
873 And once more, not excluding stuff outside m1:
874
875 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000876 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Tim Peters7402f792001-10-02 03:53:41 +0000877 (0, 8)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000878
879 The exclusion of objects from outside the designated module is
880 meant to be invoked automagically by testmod.
881
882 >>> testmod(m1)
883 (0, 3)
884
Tim Peters8a7d2d52001-01-16 07:10:57 +0000885 """
886
887 if not hasattr(d, "items"):
888 raise TypeError("Tester.rundict: d must support .items(); " +
889 `d`)
890 f = t = 0
Tim Peters24a41912001-03-21 23:07:59 +0000891 # Run the tests by alpha order of names, for consistency in
892 # verbose-mode output.
893 names = d.keys()
894 names.sort()
895 for thisname in names:
896 value = d[thisname]
Tim Peters7402f792001-10-02 03:53:41 +0000897 if _isfunction(value) or _isclass(value):
898 if module and not _from_module(module, value):
899 continue
Tim Peters8a7d2d52001-01-16 07:10:57 +0000900 f2, t2 = self.__runone(value, name + "." + thisname)
901 f = f + f2
902 t = t + t2
903 return f, t
904
905 def run__test__(self, d, name):
906 """d, name -> Treat dict d like module.__test__.
907
908 Return (#failures, #tries).
909 See testmod.__doc__ for details.
910 """
911
912 failures = tries = 0
913 prefix = name + "."
914 savepvt = self.isprivate
915 try:
916 self.isprivate = lambda *args: 0
Tim Peters24a41912001-03-21 23:07:59 +0000917 # Run the tests by alpha order of names, for consistency in
918 # verbose-mode output.
919 keys = d.keys()
920 keys.sort()
921 for k in keys:
922 v = d[k]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000923 thisname = prefix + k
Tim Peters7402f792001-10-02 03:53:41 +0000924 if type(v) in _StringTypes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000925 f, t = self.runstring(v, thisname)
Tim Peters7402f792001-10-02 03:53:41 +0000926 elif _isfunction(v) or _isclass(v):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000927 f, t = self.rundoc(v, thisname)
928 else:
929 raise TypeError("Tester.run__test__: values in "
930 "dict must be strings, functions "
931 "or classes; " + `v`)
932 failures = failures + f
933 tries = tries + t
934 finally:
935 self.isprivate = savepvt
936 return failures, tries
937
938 def summarize(self, verbose=None):
939 """
940 verbose=None -> summarize results, return (#failures, #tests).
941
942 Print summary of test results to stdout.
943 Optional arg 'verbose' controls how wordy this is. By
944 default, use the verbose setting established by the
945 constructor.
946 """
947
948 if verbose is None:
949 verbose = self.verbose
950 notests = []
951 passed = []
952 failed = []
953 totalt = totalf = 0
954 for x in self.name2ft.items():
955 name, (f, t) = x
956 assert f <= t
957 totalt = totalt + t
958 totalf = totalf + f
959 if t == 0:
960 notests.append(name)
961 elif f == 0:
962 passed.append( (name, t) )
963 else:
964 failed.append(x)
965 if verbose:
966 if notests:
967 print len(notests), "items had no tests:"
968 notests.sort()
969 for thing in notests:
970 print " ", thing
971 if passed:
972 print len(passed), "items passed all tests:"
973 passed.sort()
974 for thing, count in passed:
975 print " %3d tests in %s" % (count, thing)
976 if failed:
Guido van Rossumaf00a462001-03-18 16:58:44 +0000977 print "*" * 65
Tim Peters8a7d2d52001-01-16 07:10:57 +0000978 print len(failed), "items had failures:"
979 failed.sort()
980 for thing, (f, t) in failed:
981 print " %3d of %3d in %s" % (f, t, thing)
982 if verbose:
983 print totalt, "tests in", len(self.name2ft), "items."
984 print totalt - totalf, "passed and", totalf, "failed."
985 if totalf:
986 print "***Test Failed***", totalf, "failures."
987 elif verbose:
988 print "Test passed."
989 return totalf, totalt
990
991 def merge(self, other):
992 """
993 other -> merge in test results from the other Tester instance.
994
995 If self and other both have a test result for something
996 with the same name, the (#failures, #tests) results are
997 summed, and a warning is printed to stdout.
998
999 >>> from doctest import Tester
1000 >>> t1 = Tester(globs={}, verbose=0)
1001 >>> t1.runstring('''
1002 ... >>> x = 12
1003 ... >>> print x
1004 ... 12
1005 ... ''', "t1example")
1006 (0, 2)
1007 >>>
1008 >>> t2 = Tester(globs={}, verbose=0)
1009 >>> t2.runstring('''
1010 ... >>> x = 13
1011 ... >>> print x
1012 ... 13
1013 ... ''', "t2example")
1014 (0, 2)
1015 >>> common = ">>> assert 1 + 2 == 3\\n"
1016 >>> t1.runstring(common, "common")
1017 (0, 1)
1018 >>> t2.runstring(common, "common")
1019 (0, 1)
1020 >>> t1.merge(t2)
1021 *** Tester.merge: 'common' in both testers; summing outcomes.
1022 >>> t1.summarize(1)
1023 3 items passed all tests:
1024 2 tests in common
1025 2 tests in t1example
1026 2 tests in t2example
1027 6 tests in 3 items.
1028 6 passed and 0 failed.
1029 Test passed.
1030 (0, 6)
1031 >>>
1032 """
1033
1034 d = self.name2ft
1035 for name, (f, t) in other.name2ft.items():
Raymond Hettinger54f02222002-06-01 14:18:47 +00001036 if name in d:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001037 print "*** Tester.merge: '" + name + "' in both" \
1038 " testers; summing outcomes."
1039 f2, t2 = d[name]
1040 f = f + f2
1041 t = t + t2
1042 d[name] = f, t
1043
1044 def __record_outcome(self, name, f, t):
Raymond Hettinger54f02222002-06-01 14:18:47 +00001045 if name in self.name2ft:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001046 print "*** Warning: '" + name + "' was tested before;", \
1047 "summing outcomes."
1048 f2, t2 = self.name2ft[name]
1049 f = f + f2
1050 t = t + t2
1051 self.name2ft[name] = f, t
1052
1053 def __runone(self, target, name):
1054 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +00001055 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001056 prefix, base = name[:i], name[i+1:]
1057 else:
1058 prefix, base = "", base
1059 if self.isprivate(prefix, base):
1060 return 0, 0
1061 return self.rundoc(target, name)
1062
1063master = None
1064
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001065def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +00001066 report=True, optionflags=0):
1067 """m=None, name=None, globs=None, verbose=None, isprivate=None,
1068 report=True, optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +00001069
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001070 Test examples in docstrings in functions and classes reachable
1071 from module m (or the current module if m is not supplied), starting
1072 with m.__doc__. Private names are skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001073
1074 Also test examples reachable from dict m.__test__ if it exists and is
1075 not None. m.__dict__ maps names to functions, classes and strings;
1076 function and class docstrings are tested even if the name is private;
1077 strings are tested directly, as if they were docstrings.
1078
1079 Return (#failures, #tests).
1080
1081 See doctest.__doc__ for an overview.
1082
1083 Optional keyword arg "name" gives the name of the module; by default
1084 use m.__name__.
1085
1086 Optional keyword arg "globs" gives a dict to be used as the globals
1087 when executing examples; by default, use m.__dict__. A copy of this
1088 dict is actually used for each docstring, so that each docstring's
1089 examples start with a clean slate.
1090
1091 Optional keyword arg "verbose" prints lots of stuff if true, prints
1092 only failures if false; by default, it's true iff "-v" is in sys.argv.
1093
1094 Optional keyword arg "isprivate" specifies a function used to
1095 determine whether a name is private. The default function is
1096 doctest.is_private; see its docs for details.
1097
1098 Optional keyword arg "report" prints a summary at the end when true,
1099 else prints nothing at the end. In verbose mode, the summary is
1100 detailed, else very brief (in fact, empty if all tests passed).
1101
Tim Peters6ebe61f2003-06-27 20:48:05 +00001102 Optional keyword arg "optionflags" or's together module constants,
1103 and defaults to 0. This is new in 2.3. Possible values:
1104
1105 DONT_ACCEPT_TRUE_FOR_1
1106 By default, if an expected output block contains just "1",
1107 an actual output block containing just "True" is considered
1108 to be a match, and similarly for "0" versus "False". When
1109 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1110 is allowed.
1111
Tim Peters8a7d2d52001-01-16 07:10:57 +00001112 Advanced tomfoolery: testmod runs methods of a local instance of
1113 class doctest.Tester, then merges the results into (or creates)
1114 global Tester instance doctest.master. Methods of doctest.master
1115 can be called directly too, if you want to do something unusual.
1116 Passing report=0 to testmod is especially useful then, to delay
1117 displaying a summary. Invoke doctest.master.summarize(verbose)
1118 when you're done fiddling.
1119 """
1120
1121 global master
1122
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001123 if m is None:
1124 import sys
1125 # DWA - m will still be None if this wasn't invoked from the command
1126 # line, in which case the following TypeError is about as good an error
1127 # as we should expect
1128 m = sys.modules.get('__main__')
1129
Tim Peters7402f792001-10-02 03:53:41 +00001130 if not _ismodule(m):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001131 raise TypeError("testmod: module required; " + `m`)
1132 if name is None:
1133 name = m.__name__
Tim Peters6ebe61f2003-06-27 20:48:05 +00001134 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
1135 optionflags=optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001136 failures, tries = tester.rundoc(m, name)
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001137 f, t = tester.rundict(m.__dict__, name, m)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001138 failures += f
1139 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001140 if hasattr(m, "__test__"):
1141 testdict = m.__test__
1142 if testdict:
1143 if not hasattr(testdict, "items"):
1144 raise TypeError("testmod: module.__test__ must support "
1145 ".items(); " + `testdict`)
1146 f, t = tester.run__test__(testdict, name + ".__test__")
Tim Peters6ebe61f2003-06-27 20:48:05 +00001147 failures += f
1148 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001149 if report:
1150 tester.summarize()
1151 if master is None:
1152 master = tester
1153 else:
1154 master.merge(tester)
1155 return failures, tries
1156
Tim Petersdb3756d2003-06-29 05:30:48 +00001157###########################################################################
1158# Various doctest extensions, to make using doctest with unittest
1159# easier, and to help debugging when a doctest goes wrong. Original
1160# code by Jim Fulton.
1161
1162# Utilities.
1163
1164# If module is None, return the calling module (the module that called
1165# the routine that called _normalize_module -- this normally won't be
1166# doctest!). If module is a string, it should be the (possibly dotted)
1167# name of a module, and the (rightmost) module object is returned. Else
1168# module is returned untouched; the intent appears to be that module is
1169# already a module object in this case (although this isn't checked).
1170
1171def _normalize_module(module):
1172 import sys
1173
1174 if module is None:
1175 # Get our caller's caller's module.
1176 module = sys._getframe(2).f_globals['__name__']
1177 module = sys.modules[module]
1178
1179 elif isinstance(module, (str, unicode)):
1180 # The ["*"] at the end is a mostly meaningless incantation with
1181 # a crucial property: if, e.g., module is 'a.b.c', it convinces
1182 # __import__ to return c instead of a.
1183 module = __import__(module, globals(), locals(), ["*"])
1184
1185 return module
1186
1187# tests is a list of (testname, docstring, filename, lineno) tuples.
1188# If object has a __doc__ attr, and the __doc__ attr looks like it
1189# contains a doctest (specifically, if it contains an instance of '>>>'),
1190# then tuple
1191# prefix + name, object.__doc__, filename, lineno
1192# is appended to tests. Else tests is left alone.
1193# There is no return value.
1194
1195def _get_doctest(name, object, tests, prefix, filename='', lineno=''):
1196 doc = getattr(object, '__doc__', '')
1197 if isinstance(doc, basestring) and '>>>' in doc:
1198 tests.append((prefix + name, doc, filename, lineno))
1199
1200# tests is a list of (testname, docstring, filename, lineno) tuples.
1201# docstrings containing doctests are appended to tests (if any are found).
1202# items is a dict, like a module or class dict, mapping strings to objects.
1203# mdict is the global dict of a "home" module -- only objects belonging
1204# to this module are searched for docstrings. module is the module to
1205# which mdict belongs.
1206# prefix is a string to be prepended to an object's name when adding a
1207# tuple to tests.
1208# The objects (values) in items are examined (recursively), and doctests
1209# belonging to functions and classes in the home module are appended to
1210# tests.
1211# minlineno is a gimmick to try to guess the file-relative line number
1212# at which a doctest probably begins.
1213
1214def _extract_doctests(items, module, mdict, tests, prefix, minlineno=0):
1215
1216 for name, object in items:
1217 # Only interested in named objects.
1218 if not hasattr(object, '__name__'):
1219 continue
1220
1221 elif hasattr(object, 'func_globals'):
1222 # Looks like a function.
1223 if object.func_globals is not mdict:
1224 # Non-local function.
1225 continue
1226 code = getattr(object, 'func_code', None)
1227 filename = getattr(code, 'co_filename', '')
1228 lineno = getattr(code, 'co_firstlineno', -1) + 1
1229 if minlineno:
1230 minlineno = min(lineno, minlineno)
1231 else:
1232 minlineno = lineno
1233 _get_doctest(name, object, tests, prefix, filename, lineno)
1234
1235 elif hasattr(object, "__module__"):
1236 # Maybe a class-like thing, in which case we care.
1237 if object.__module__ != module.__name__:
1238 # Not the same module.
1239 continue
1240 if not (hasattr(object, '__dict__')
1241 and hasattr(object, '__bases__')):
1242 # Not a class.
1243 continue
1244
1245 lineno = _extract_doctests(object.__dict__.items(),
1246 module,
1247 mdict,
1248 tests,
1249 prefix + name + ".")
1250 # XXX "-3" is unclear.
1251 _get_doctest(name, object, tests, prefix,
1252 lineno="%s (or above)" % (lineno - 3))
1253
1254 return minlineno
1255
1256# Find all the doctests belonging to the module object.
1257# Return a list of
1258# (testname, docstring, filename, lineno)
1259# tuples.
1260
1261def _find_tests(module, prefix=None):
1262 if prefix is None:
1263 prefix = module.__name__
1264 mdict = module.__dict__
1265 tests = []
1266 # Get the module-level doctest (if any).
1267 _get_doctest(prefix, module, tests, '', lineno="1 (or above)")
1268 # Recursively search the module __dict__ for doctests.
1269 if prefix:
1270 prefix += "."
1271 _extract_doctests(mdict.items(), module, mdict, tests, prefix)
1272 return tests
1273
1274# unittest helpers.
1275
1276# A function passed to unittest, for unittest to drive.
1277# tester is doctest Tester instance. doc is the docstring whose
1278# doctests are to be run.
1279
1280def _utest(tester, name, doc, filename, lineno):
1281 import sys
1282 from StringIO import StringIO
1283
1284 old = sys.stdout
1285 sys.stdout = new = StringIO()
1286 try:
1287 failures, tries = tester.runstring(doc, name)
1288 finally:
1289 sys.stdout = old
1290
1291 if failures:
1292 msg = new.getvalue()
1293 lname = '.'.join(name.split('.')[-1:])
1294 if not lineno:
1295 lineno = "0 (don't know line number)"
1296 # Don't change this format! It was designed so that Emacs can
1297 # parse it naturally.
1298 raise DocTestTestFailure('Failed doctest test for %s\n'
1299 ' File "%s", line %s, in %s\n\n%s' %
1300 (name, filename, lineno, lname, msg))
1301
1302class DocTestTestFailure(Exception):
1303 """A doctest test failed"""
1304
1305def DocTestSuite(module=None):
1306 """Convert doctest tests for a module to a unittest TestSuite.
1307
1308 The returned TestSuite is to be run by the unittest framework, and
1309 runs each doctest in the module. If any of the doctests fail,
1310 then the synthesized unit test fails, and an error is raised showing
1311 the name of the file containing the test and a (sometimes approximate)
1312 line number.
1313
1314 The optional module argument provides the module to be tested. It
1315 can be a module object or a (possibly dotted) module name. If not
1316 specified, the module calling DocTestSuite() is used.
1317
1318 Example (although note that unittest supplies many ways to use the
1319 TestSuite returned; see the unittest docs):
1320
1321 import unittest
1322 import doctest
1323 import my_module_with_doctests
1324
1325 suite = doctest.DocTestSuite(my_module_with_doctests)
1326 runner = unittest.TextTestRunner()
1327 runner.run(suite)
1328 """
1329
1330 import unittest
1331
1332 module = _normalize_module(module)
1333 tests = _find_tests(module)
1334 if not tests:
1335 raise ValueError(module, "has no tests")
1336
1337 tests.sort()
1338 suite = unittest.TestSuite()
1339 tester = Tester(module)
1340 for name, doc, filename, lineno in tests:
1341 if not filename:
1342 filename = module.__file__
1343 if filename.endswith(".pyc"):
1344 filename = filename[:-1]
1345 elif filename.endswith(".pyo"):
1346 filename = filename[:-1]
1347 def runit(name=name, doc=doc, filename=filename, lineno=lineno):
1348 _utest(tester, name, doc, filename, lineno)
1349 suite.addTest(unittest.FunctionTestCase(
1350 runit,
1351 description="doctest of " + name))
1352 return suite
1353
1354# Debugging support.
1355
1356def _expect(expect):
1357 # Return the expected output (if any), formatted as a Python
1358 # comment block.
1359 if expect:
1360 expect = "\n# ".join(expect.split("\n"))
1361 expect = "\n# Expect:\n# %s" % expect
1362 return expect
1363
1364def testsource(module, name):
1365 """Extract the doctest examples from a docstring.
1366
1367 Provide the module (or dotted name of the module) containing the
1368 tests to be extracted, and the name (within the module) of the object
1369 with the docstring containing the tests to be extracted.
1370
1371 The doctest examples are returned as a string containing Python
1372 code. The expected output blocks in the examples are converted
1373 to Python comments.
1374 """
1375
1376 module = _normalize_module(module)
1377 tests = _find_tests(module, "")
1378 test = [doc for (tname, doc, dummy, dummy) in tests
1379 if tname == name]
1380 if not test:
1381 raise ValueError(name, "not found in tests")
1382 test = test[0]
1383 examples = [source + _expect(expect)
1384 for source, expect, dummy in _extract_examples(test)]
1385 return '\n'.join(examples)
1386
1387def debug(module, name):
1388 """Debug a single docstring containing doctests.
1389
1390 Provide the module (or dotted name of the module) containing the
1391 docstring to be debugged, and the name (within the module) of the
1392 object with the docstring to be debugged.
1393
1394 The doctest examples are extracted (see function testsource()),
1395 and written to a temp file. The Python debugger (pdb) is then
1396 invoked on that file.
1397 """
1398
1399 import os
1400 import pdb
1401 import tempfile
1402
1403 module = _normalize_module(module)
1404 testsrc = testsource(module, name)
1405 srcfilename = tempfile.mktemp("doctestdebug.py")
1406 f = file(srcfilename, 'w')
1407 f.write(testsrc)
1408 f.close()
1409
1410 globs = {}
1411 globs.update(module.__dict__)
1412 try:
1413 # Note that %r is vital here. '%s' instead can, e.g., cause
1414 # backslashes to get treated as metacharacters on Windows.
1415 pdb.run("execfile(%r)" % srcfilename, globs, globs)
1416 finally:
1417 os.remove(srcfilename)
1418
1419
1420
Tim Peters8a7d2d52001-01-16 07:10:57 +00001421class _TestClass:
1422 """
1423 A pointless class, for sanity-checking of docstring testing.
1424
1425 Methods:
1426 square()
1427 get()
1428
1429 >>> _TestClass(13).get() + _TestClass(-12).get()
1430 1
1431 >>> hex(_TestClass(13).square().get())
1432 '0xa9'
1433 """
1434
1435 def __init__(self, val):
1436 """val -> _TestClass object with associated value val.
1437
1438 >>> t = _TestClass(123)
1439 >>> print t.get()
1440 123
1441 """
1442
1443 self.val = val
1444
1445 def square(self):
1446 """square() -> square TestClass's associated value
1447
1448 >>> _TestClass(13).square().get()
1449 169
1450 """
1451
1452 self.val = self.val ** 2
1453 return self
1454
1455 def get(self):
1456 """get() -> return TestClass's associated value.
1457
1458 >>> x = _TestClass(-42)
1459 >>> print x.get()
1460 -42
1461 """
1462
1463 return self.val
1464
1465__test__ = {"_TestClass": _TestClass,
1466 "string": r"""
1467 Example of a string object, searched as-is.
1468 >>> x = 1; y = 2
1469 >>> x + y, x * y
1470 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001471 """,
1472 "bool-int equivalence": r"""
1473 In 2.2, boolean expressions displayed
1474 0 or 1. By default, we still accept
1475 them. This can be disabled by passing
1476 DONT_ACCEPT_TRUE_FOR_1 to the new
1477 optionflags argument.
1478 >>> 4 == 4
1479 1
1480 >>> 4 == 4
1481 True
1482 >>> 4 > 4
1483 0
1484 >>> 4 > 4
1485 False
1486 """,
Tim Peters8a7d2d52001-01-16 07:10:57 +00001487 }
1488
1489def _test():
1490 import doctest
1491 return doctest.testmod(doctest)
1492
1493if __name__ == "__main__":
1494 _test()