blob: 979d6d04f2233933e6ebc4c9197730fc5d5d4533 [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',
Raymond Hettingercc39a132003-07-11 22:36:52 +0000284 'master',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000285]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000286
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000287import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000288
Tim Peters8a7d2d52001-01-16 07:10:57 +0000289import re
290PS1 = ">>>"
291PS2 = "..."
292_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
293_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
294_isEmpty = re.compile(r"\s*$").match
295_isComment = re.compile(r"\s*#").match
296del re
297
Tim Peters7402f792001-10-02 03:53:41 +0000298from types import StringTypes as _StringTypes
299
300from inspect import isclass as _isclass
301from inspect import isfunction as _isfunction
302from inspect import ismodule as _ismodule
Tim Peters17111f32001-10-03 04:08:26 +0000303from inspect import classify_class_attrs as _classify_class_attrs
Tim Peters7402f792001-10-02 03:53:41 +0000304
Tim Peters6ebe61f2003-06-27 20:48:05 +0000305# Option constants.
306DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
307
Tim Peters8a7d2d52001-01-16 07:10:57 +0000308# Extract interactive examples from a string. Return a list of triples,
309# (source, outcome, lineno). "source" is the source code, and ends
310# with a newline iff the source spans more than one line. "outcome" is
311# the expected output if any, else an empty string. When not empty,
312# outcome always ends with a newline. "lineno" is the line number,
313# 0-based wrt the start of the string, of the first source line.
314
315def _extract_examples(s):
316 isPS1, isPS2 = _isPS1, _isPS2
317 isEmpty, isComment = _isEmpty, _isComment
318 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000319 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000320 i, n = 0, len(lines)
321 while i < n:
322 line = lines[i]
323 i = i + 1
324 m = isPS1(line)
325 if m is None:
326 continue
327 j = m.end(0) # beyond the prompt
328 if isEmpty(line, j) or isComment(line, j):
329 # a bare prompt or comment -- not interesting
330 continue
331 lineno = i - 1
332 if line[j] != " ":
333 raise ValueError("line " + `lineno` + " of docstring lacks "
334 "blank after " + PS1 + ": " + line)
335 j = j + 1
336 blanks = m.group(1)
337 nblanks = len(blanks)
338 # suck up this and following PS2 lines
339 source = []
340 while 1:
341 source.append(line[j:])
342 line = lines[i]
343 m = isPS2(line)
344 if m:
345 if m.group(1) != blanks:
346 raise ValueError("inconsistent leading whitespace "
347 "in line " + `i` + " of docstring: " + line)
348 i = i + 1
349 else:
350 break
351 if len(source) == 1:
352 source = source[0]
353 else:
354 # get rid of useless null line from trailing empty "..."
355 if source[-1] == "":
356 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000357 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000358 # suck up response
359 if isPS1(line) or isEmpty(line):
360 expect = ""
361 else:
362 expect = []
363 while 1:
364 if line[:nblanks] != blanks:
365 raise ValueError("inconsistent leading whitespace "
366 "in line " + `i` + " of docstring: " + line)
367 expect.append(line[nblanks:])
368 i = i + 1
369 line = lines[i]
370 if isPS1(line) or isEmpty(line):
371 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000372 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000373 examples.append( (source, expect, lineno) )
374 return examples
375
376# Capture stdout when running examples.
377
378class _SpoofOut:
379 def __init__(self):
380 self.clear()
381 def write(self, s):
382 self.buf.append(s)
383 def get(self):
Tim Petersf9bb4962001-02-14 06:35:35 +0000384 guts = "".join(self.buf)
385 # If anything at all was written, make sure there's a trailing
386 # newline. There's no way for the expected output to indicate
387 # that a trailing newline is missing.
388 if guts and not guts.endswith("\n"):
389 guts = guts + "\n"
Tim Petersc77db342001-10-23 02:21:52 +0000390 # Prevent softspace from screwing up the next test case, in
391 # case they used print with a trailing comma in an example.
392 if hasattr(self, "softspace"):
393 del self.softspace
Tim Petersf9bb4962001-02-14 06:35:35 +0000394 return guts
Tim Peters8a7d2d52001-01-16 07:10:57 +0000395 def clear(self):
396 self.buf = []
Tim Petersc77db342001-10-23 02:21:52 +0000397 if hasattr(self, "softspace"):
398 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000399 def flush(self):
400 # JPython calls flush
401 pass
402
403# Display some tag-and-msg pairs nicely, keeping the tag and its msg
404# on the same line when that makes sense.
405
406def _tag_out(printer, *tag_msg_pairs):
407 for tag, msg in tag_msg_pairs:
408 printer(tag + ":")
409 msg_has_nl = msg[-1:] == "\n"
410 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000411 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000412 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
413 printer(" ")
414 else:
415 printer("\n")
416 printer(msg)
417 if not msg_has_nl:
418 printer("\n")
419
420# Run list of examples, in context globs. "out" can be used to display
421# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
422# that captures the examples' std output. Return (#failures, #tries).
423
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000424def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000425 compileflags, optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000426 import sys, traceback
427 OK, BOOM, FAIL = range(3)
428 NADA = "nothing"
429 stderr = _SpoofOut()
430 failures = 0
431 for source, want, lineno in examples:
432 if verbose:
433 _tag_out(out, ("Trying", source),
434 ("Expecting", want or NADA))
435 fakeout.clear()
436 try:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000437 exec compile(source, "<string>", "single",
438 compileflags, 1) in globs
Tim Peters8a7d2d52001-01-16 07:10:57 +0000439 got = fakeout.get()
440 state = OK
Tim Petersbcc2c122002-03-20 19:32:03 +0000441 except KeyboardInterrupt:
442 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000443 except:
444 # See whether the exception was expected.
Tim Petersea4f9312001-02-13 20:54:42 +0000445 if want.find("Traceback (innermost last):\n") == 0 or \
446 want.find("Traceback (most recent call last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000447 # Only compare exception type and value - the rest of
448 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000449 want = want.split('\n')[-2] + '\n'
Tim Peters77f2d502001-06-24 18:59:01 +0000450 exc_type, exc_val = sys.exc_info()[:2]
Tim Peters08bba952001-06-24 06:46:58 +0000451 got = traceback.format_exception_only(exc_type, exc_val)[-1]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000452 state = OK
453 else:
454 # unexpected exception
455 stderr.clear()
456 traceback.print_exc(file=stderr)
457 state = BOOM
458
459 if state == OK:
Tim Peters6ebe61f2003-06-27 20:48:05 +0000460 if (got == want or
461 (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and
462 (got, want) in (("True\n", "1\n"), ("False\n", "0\n"))
463 )
464 ):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000465 if verbose:
466 out("ok\n")
467 continue
468 state = FAIL
469
470 assert state in (FAIL, BOOM)
471 failures = failures + 1
472 out("*" * 65 + "\n")
473 _tag_out(out, ("Failure in example", source))
474 out("from line #" + `lineno` + " of " + name + "\n")
475 if state == FAIL:
476 _tag_out(out, ("Expected", want or NADA), ("Got", got))
477 else:
478 assert state == BOOM
479 _tag_out(out, ("Exception raised", stderr.get()))
480
481 return failures, len(examples)
482
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000483# Get the future-flags associated with the future features that have been
484# imported into globs.
485
486def _extract_future_flags(globs):
487 flags = 0
488 for fname in __future__.all_feature_names:
489 feature = globs.get(fname, None)
490 if feature is getattr(__future__, fname):
491 flags |= feature.compiler_flag
492 return flags
493
Tim Petersd4ad59e2001-06-24 20:02:47 +0000494# Run list of examples, in a shallow copy of context (dict) globs.
495# Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000496
Tim Peters6ebe61f2003-06-27 20:48:05 +0000497def _run_examples(examples, globs, verbose, name, compileflags,
498 optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000499 import sys
500 saveout = sys.stdout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000501 globs = globs.copy()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000502 try:
503 sys.stdout = fakeout = _SpoofOut()
504 x = _run_examples_inner(saveout.write, fakeout, examples,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000505 globs, verbose, name, compileflags,
506 optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000507 finally:
508 sys.stdout = saveout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000509 # While Python gc can clean up most cycles on its own, it doesn't
510 # chase frame objects. This is especially irksome when running
511 # generator tests that raise exceptions, because a named generator-
512 # iterator gets an entry in globs, and the generator-iterator
513 # object's frame's traceback info points back to globs. This is
Tim Petersfee69d02001-06-24 20:24:16 +0000514 # easy to break just by clearing the namespace. This can also
515 # help to break other kinds of cycles, and even for cycles that
516 # gc can break itself it's better to break them ASAP.
Tim Petersd4ad59e2001-06-24 20:02:47 +0000517 globs.clear()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000518 return x
519
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000520def run_docstring_examples(f, globs, verbose=0, name="NoName",
Tim Peters6ebe61f2003-06-27 20:48:05 +0000521 compileflags=None, optionflags=0):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000522 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
523
Tim Petersd4ad59e2001-06-24 20:02:47 +0000524 Use (a shallow copy of) dict globs as the globals for execution.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000525 Return (#failures, #tries).
526
527 If optional arg verbose is true, print stuff even if there are no
528 failures.
529 Use string name in failure msgs.
530 """
531
532 try:
533 doc = f.__doc__
534 if not doc:
535 # docstring empty or None
536 return 0, 0
537 # just in case CT invents a doc object that has to be forced
538 # to look like a string <0.9 wink>
539 doc = str(doc)
Tim Petersbcc2c122002-03-20 19:32:03 +0000540 except KeyboardInterrupt:
541 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000542 except:
543 return 0, 0
544
545 e = _extract_examples(doc)
546 if not e:
547 return 0, 0
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000548 if compileflags is None:
549 compileflags = _extract_future_flags(globs)
Tim Peters6ebe61f2003-06-27 20:48:05 +0000550 return _run_examples(e, globs, verbose, name, compileflags, optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000551
552def is_private(prefix, base):
553 """prefix, base -> true iff name prefix + "." + base is "private".
554
555 Prefix may be an empty string, and base does not contain a period.
556 Prefix is ignored (although functions you write conforming to this
557 protocol may make use of it).
558 Return true iff base begins with an (at least one) underscore, but
559 does not both begin and end with (at least) two underscores.
560
561 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000562 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000563 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000564 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000565 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000566 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000567 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000568 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000569 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000570 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000571 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000572 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000573 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000574 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000575 """
576
577 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
578
Tim Peters7402f792001-10-02 03:53:41 +0000579# Determine if a class of function was defined in the given module.
580
581def _from_module(module, object):
582 if _isfunction(object):
583 return module.__dict__ is object.func_globals
584 if _isclass(object):
585 return module.__name__ == object.__module__
586 raise ValueError("object must be a class or function")
587
Tim Peters8a7d2d52001-01-16 07:10:57 +0000588class Tester:
589 """Class Tester -- runs docstring examples and accumulates stats.
590
591In normal use, function doctest.testmod() hides all this from you,
592so use that if you can. Create your own instances of Tester to do
593fancier things.
594
595Methods:
596 runstring(s, name)
597 Search string s for examples to run; use name for logging.
598 Return (#failures, #tries).
599
600 rundoc(object, name=None)
601 Search object.__doc__ for examples to run; use name (or
602 object.__name__) for logging. Return (#failures, #tries).
603
Tim Peters7402f792001-10-02 03:53:41 +0000604 rundict(d, name, module=None)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000605 Search for examples in docstrings in all of d.values(); use name
Tim Peters7402f792001-10-02 03:53:41 +0000606 for logging. Exclude functions and classes not defined in module
607 if specified. Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000608
609 run__test__(d, name)
610 Treat dict d like module.__test__. Return (#failures, #tries).
611
612 summarize(verbose=None)
613 Display summary of testing results, to stdout. Return
614 (#failures, #tries).
615
616 merge(other)
617 Merge in the test results from Tester instance "other".
618
619>>> from doctest import Tester
620>>> t = Tester(globs={'x': 42}, verbose=0)
621>>> t.runstring(r'''
622... >>> x = x * 2
623... >>> print x
624... 42
625... ''', 'XYZ')
626*****************************************************************
627Failure in example: print x
628from line #2 of XYZ
629Expected: 42
630Got: 84
631(1, 2)
632>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
633(0, 2)
634>>> t.summarize()
Guido van Rossum261d91a2001-03-18 17:05:58 +0000635*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006361 items had failures:
637 1 of 2 in XYZ
638***Test Failed*** 1 failures.
639(1, 4)
640>>> t.summarize(verbose=1)
6411 items passed all tests:
642 2 tests in example2
Guido van Rossum261d91a2001-03-18 17:05:58 +0000643*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006441 items had failures:
645 1 of 2 in XYZ
6464 tests in 2 items.
6473 passed and 1 failed.
648***Test Failed*** 1 failures.
649(1, 4)
650>>>
651"""
652
653 def __init__(self, mod=None, globs=None, verbose=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000654 isprivate=None, optionflags=0):
655 """mod=None, globs=None, verbose=None, isprivate=None,
656optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000657
658See doctest.__doc__ for an overview.
659
660Optional keyword arg "mod" is a module, whose globals are used for
661executing examples. If not specified, globs must be specified.
662
663Optional keyword arg "globs" gives a dict to be used as the globals
664when executing examples; if not specified, use the globals from
665module mod.
666
667In either case, a copy of the dict is used for each docstring
668examined.
669
670Optional keyword arg "verbose" prints lots of stuff if true, only
671failures if false; by default, it's true iff "-v" is in sys.argv.
672
673Optional keyword arg "isprivate" specifies a function used to determine
674whether a name is private. The default function is doctest.is_private;
675see its docs for details.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000676
677See doctest.testmod docs for the meaning of optionflags.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000678"""
679
680 if mod is None and globs is None:
681 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters7402f792001-10-02 03:53:41 +0000682 if mod is not None and not _ismodule(mod):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000683 raise TypeError("Tester.__init__: mod must be a module; " +
684 `mod`)
685 if globs is None:
686 globs = mod.__dict__
687 self.globs = globs
688
689 if verbose is None:
690 import sys
691 verbose = "-v" in sys.argv
692 self.verbose = verbose
693
694 if isprivate is None:
695 isprivate = is_private
696 self.isprivate = isprivate
697
Tim Peters6ebe61f2003-06-27 20:48:05 +0000698 self.optionflags = optionflags
699
Tim Peters8a7d2d52001-01-16 07:10:57 +0000700 self.name2ft = {} # map name to (#failures, #trials) pair
701
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000702 self.compileflags = _extract_future_flags(globs)
703
Tim Peters8a7d2d52001-01-16 07:10:57 +0000704 def runstring(self, s, name):
705 """
706 s, name -> search string s for examples to run, logging as name.
707
708 Use string name as the key for logging the outcome.
709 Return (#failures, #examples).
710
711 >>> t = Tester(globs={}, verbose=1)
712 >>> test = r'''
713 ... # just an example
714 ... >>> x = 1 + 2
715 ... >>> x
716 ... 3
717 ... '''
718 >>> t.runstring(test, "Example")
719 Running string Example
720 Trying: x = 1 + 2
721 Expecting: nothing
722 ok
723 Trying: x
724 Expecting: 3
725 ok
726 0 of 2 examples failed in string Example
727 (0, 2)
728 """
729
730 if self.verbose:
731 print "Running string", name
732 f = t = 0
733 e = _extract_examples(s)
734 if e:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000735 f, t = _run_examples(e, self.globs, self.verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000736 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000737 if self.verbose:
738 print f, "of", t, "examples failed in string", name
739 self.__record_outcome(name, f, t)
740 return f, t
741
742 def rundoc(self, object, name=None):
743 """
744 object, name=None -> search object.__doc__ for examples to run.
745
746 Use optional string name as the key for logging the outcome;
747 by default use object.__name__.
748 Return (#failures, #examples).
749 If object is a class object, search recursively for method
750 docstrings too.
751 object.__doc__ is examined regardless of name, but if object is
752 a class, whether private names reached from object are searched
753 depends on the constructor's "isprivate" argument.
754
755 >>> t = Tester(globs={}, verbose=0)
756 >>> def _f():
757 ... '''Trivial docstring example.
758 ... >>> assert 2 == 2
759 ... '''
760 ... return 32
761 ...
762 >>> t.rundoc(_f) # expect 0 failures in 1 example
763 (0, 1)
764 """
765
766 if name is None:
767 try:
768 name = object.__name__
769 except AttributeError:
770 raise ValueError("Tester.rundoc: name must be given "
771 "when object.__name__ doesn't exist; " + `object`)
772 if self.verbose:
773 print "Running", name + ".__doc__"
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000774 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
Tim Peters275abbd2003-06-29 03:11:20 +0000775 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000776 if self.verbose:
777 print f, "of", t, "examples failed in", name + ".__doc__"
778 self.__record_outcome(name, f, t)
Tim Peters7402f792001-10-02 03:53:41 +0000779 if _isclass(object):
Tim Peters17111f32001-10-03 04:08:26 +0000780 # In 2.2, class and static methods complicate life. Build
781 # a dict "that works", by hook or by crook.
782 d = {}
783 for tag, kind, homecls, value in _classify_class_attrs(object):
784
785 if homecls is not object:
786 # Only look at names defined immediately by the class.
787 continue
788
789 elif self.isprivate(name, tag):
790 continue
791
792 elif kind == "method":
793 # value is already a function
794 d[tag] = value
795
796 elif kind == "static method":
797 # value isn't a function, but getattr reveals one
798 d[tag] = getattr(object, tag)
799
800 elif kind == "class method":
801 # Hmm. A classmethod object doesn't seem to reveal
802 # enough. But getattr turns it into a bound method,
803 # and from there .im_func retrieves the underlying
804 # function.
805 d[tag] = getattr(object, tag).im_func
806
807 elif kind == "property":
808 # The methods implementing the property have their
809 # own docstrings -- but the property may have one too.
810 if value.__doc__ is not None:
811 d[tag] = str(value.__doc__)
812
813 elif kind == "data":
814 # Grab nested classes.
815 if _isclass(value):
816 d[tag] = value
817
818 else:
819 raise ValueError("teach doctest about %r" % kind)
820
821 f2, t2 = self.run__test__(d, name)
822 f += f2
823 t += t2
824
Tim Peters8a7d2d52001-01-16 07:10:57 +0000825 return f, t
826
Tim Peters7402f792001-10-02 03:53:41 +0000827 def rundict(self, d, name, module=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000828 """
Tim Peters7402f792001-10-02 03:53:41 +0000829 d, name, module=None -> search for docstring examples in d.values().
Tim Peters8a7d2d52001-01-16 07:10:57 +0000830
831 For k, v in d.items() such that v is a function or class,
832 do self.rundoc(v, name + "." + k). Whether this includes
833 objects with private names depends on the constructor's
Tim Peters7402f792001-10-02 03:53:41 +0000834 "isprivate" argument. If module is specified, functions and
835 classes that are not defined in module are excluded.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000836 Return aggregate (#failures, #examples).
837
Tim Peters7402f792001-10-02 03:53:41 +0000838 Build and populate two modules with sample functions to test that
839 exclusion of external functions and classes works.
840
841 >>> import new
842 >>> m1 = new.module('_m1')
843 >>> m2 = new.module('_m2')
844 >>> test_data = \"""
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000845 ... def _f():
Tim Peters7402f792001-10-02 03:53:41 +0000846 ... '''>>> assert 1 == 1
847 ... '''
848 ... def g():
Tim Peters8a7d2d52001-01-16 07:10:57 +0000849 ... '''>>> assert 2 != 1
850 ... '''
Tim Peters7402f792001-10-02 03:53:41 +0000851 ... class H:
852 ... '''>>> assert 2 > 1
853 ... '''
854 ... def bar(self):
855 ... '''>>> assert 1 < 2
856 ... '''
857 ... \"""
858 >>> exec test_data in m1.__dict__
859 >>> exec test_data in m2.__dict__
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000860 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tim Peters7402f792001-10-02 03:53:41 +0000861
862 Tests that objects outside m1 are excluded:
863
Tim Peters8a7d2d52001-01-16 07:10:57 +0000864 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000865 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000866 (0, 3)
867
868 Again, but with a custom isprivate function allowing _f:
869
Tim Peters8a7d2d52001-01-16 07:10:57 +0000870 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000871 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000872 (0, 4)
873
874 And once more, not excluding stuff outside m1:
875
876 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000877 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Tim Peters7402f792001-10-02 03:53:41 +0000878 (0, 8)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000879
880 The exclusion of objects from outside the designated module is
881 meant to be invoked automagically by testmod.
882
883 >>> testmod(m1)
884 (0, 3)
885
Tim Peters8a7d2d52001-01-16 07:10:57 +0000886 """
887
888 if not hasattr(d, "items"):
889 raise TypeError("Tester.rundict: d must support .items(); " +
890 `d`)
891 f = t = 0
Tim Peters24a41912001-03-21 23:07:59 +0000892 # Run the tests by alpha order of names, for consistency in
893 # verbose-mode output.
894 names = d.keys()
895 names.sort()
896 for thisname in names:
897 value = d[thisname]
Tim Peters7402f792001-10-02 03:53:41 +0000898 if _isfunction(value) or _isclass(value):
899 if module and not _from_module(module, value):
900 continue
Tim Peters8a7d2d52001-01-16 07:10:57 +0000901 f2, t2 = self.__runone(value, name + "." + thisname)
902 f = f + f2
903 t = t + t2
904 return f, t
905
906 def run__test__(self, d, name):
907 """d, name -> Treat dict d like module.__test__.
908
909 Return (#failures, #tries).
910 See testmod.__doc__ for details.
911 """
912
913 failures = tries = 0
914 prefix = name + "."
915 savepvt = self.isprivate
916 try:
917 self.isprivate = lambda *args: 0
Tim Peters24a41912001-03-21 23:07:59 +0000918 # Run the tests by alpha order of names, for consistency in
919 # verbose-mode output.
920 keys = d.keys()
921 keys.sort()
922 for k in keys:
923 v = d[k]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000924 thisname = prefix + k
Tim Peters7402f792001-10-02 03:53:41 +0000925 if type(v) in _StringTypes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000926 f, t = self.runstring(v, thisname)
Tim Peters7402f792001-10-02 03:53:41 +0000927 elif _isfunction(v) or _isclass(v):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000928 f, t = self.rundoc(v, thisname)
929 else:
930 raise TypeError("Tester.run__test__: values in "
931 "dict must be strings, functions "
932 "or classes; " + `v`)
933 failures = failures + f
934 tries = tries + t
935 finally:
936 self.isprivate = savepvt
937 return failures, tries
938
939 def summarize(self, verbose=None):
940 """
941 verbose=None -> summarize results, return (#failures, #tests).
942
943 Print summary of test results to stdout.
944 Optional arg 'verbose' controls how wordy this is. By
945 default, use the verbose setting established by the
946 constructor.
947 """
948
949 if verbose is None:
950 verbose = self.verbose
951 notests = []
952 passed = []
953 failed = []
954 totalt = totalf = 0
955 for x in self.name2ft.items():
956 name, (f, t) = x
957 assert f <= t
958 totalt = totalt + t
959 totalf = totalf + f
960 if t == 0:
961 notests.append(name)
962 elif f == 0:
963 passed.append( (name, t) )
964 else:
965 failed.append(x)
966 if verbose:
967 if notests:
968 print len(notests), "items had no tests:"
969 notests.sort()
970 for thing in notests:
971 print " ", thing
972 if passed:
973 print len(passed), "items passed all tests:"
974 passed.sort()
975 for thing, count in passed:
976 print " %3d tests in %s" % (count, thing)
977 if failed:
Guido van Rossumaf00a462001-03-18 16:58:44 +0000978 print "*" * 65
Tim Peters8a7d2d52001-01-16 07:10:57 +0000979 print len(failed), "items had failures:"
980 failed.sort()
981 for thing, (f, t) in failed:
982 print " %3d of %3d in %s" % (f, t, thing)
983 if verbose:
984 print totalt, "tests in", len(self.name2ft), "items."
985 print totalt - totalf, "passed and", totalf, "failed."
986 if totalf:
987 print "***Test Failed***", totalf, "failures."
988 elif verbose:
989 print "Test passed."
990 return totalf, totalt
991
992 def merge(self, other):
993 """
994 other -> merge in test results from the other Tester instance.
995
996 If self and other both have a test result for something
997 with the same name, the (#failures, #tests) results are
998 summed, and a warning is printed to stdout.
999
1000 >>> from doctest import Tester
1001 >>> t1 = Tester(globs={}, verbose=0)
1002 >>> t1.runstring('''
1003 ... >>> x = 12
1004 ... >>> print x
1005 ... 12
1006 ... ''', "t1example")
1007 (0, 2)
1008 >>>
1009 >>> t2 = Tester(globs={}, verbose=0)
1010 >>> t2.runstring('''
1011 ... >>> x = 13
1012 ... >>> print x
1013 ... 13
1014 ... ''', "t2example")
1015 (0, 2)
1016 >>> common = ">>> assert 1 + 2 == 3\\n"
1017 >>> t1.runstring(common, "common")
1018 (0, 1)
1019 >>> t2.runstring(common, "common")
1020 (0, 1)
1021 >>> t1.merge(t2)
1022 *** Tester.merge: 'common' in both testers; summing outcomes.
1023 >>> t1.summarize(1)
1024 3 items passed all tests:
1025 2 tests in common
1026 2 tests in t1example
1027 2 tests in t2example
1028 6 tests in 3 items.
1029 6 passed and 0 failed.
1030 Test passed.
1031 (0, 6)
1032 >>>
1033 """
1034
1035 d = self.name2ft
1036 for name, (f, t) in other.name2ft.items():
Raymond Hettinger54f02222002-06-01 14:18:47 +00001037 if name in d:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001038 print "*** Tester.merge: '" + name + "' in both" \
1039 " testers; summing outcomes."
1040 f2, t2 = d[name]
1041 f = f + f2
1042 t = t + t2
1043 d[name] = f, t
1044
1045 def __record_outcome(self, name, f, t):
Raymond Hettinger54f02222002-06-01 14:18:47 +00001046 if name in self.name2ft:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001047 print "*** Warning: '" + name + "' was tested before;", \
1048 "summing outcomes."
1049 f2, t2 = self.name2ft[name]
1050 f = f + f2
1051 t = t + t2
1052 self.name2ft[name] = f, t
1053
1054 def __runone(self, target, name):
1055 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +00001056 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001057 prefix, base = name[:i], name[i+1:]
1058 else:
1059 prefix, base = "", base
1060 if self.isprivate(prefix, base):
1061 return 0, 0
1062 return self.rundoc(target, name)
1063
1064master = None
1065
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001066def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +00001067 report=True, optionflags=0):
1068 """m=None, name=None, globs=None, verbose=None, isprivate=None,
1069 report=True, optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +00001070
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001071 Test examples in docstrings in functions and classes reachable
1072 from module m (or the current module if m is not supplied), starting
1073 with m.__doc__. Private names are skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001074
1075 Also test examples reachable from dict m.__test__ if it exists and is
1076 not None. m.__dict__ maps names to functions, classes and strings;
1077 function and class docstrings are tested even if the name is private;
1078 strings are tested directly, as if they were docstrings.
1079
1080 Return (#failures, #tests).
1081
1082 See doctest.__doc__ for an overview.
1083
1084 Optional keyword arg "name" gives the name of the module; by default
1085 use m.__name__.
1086
1087 Optional keyword arg "globs" gives a dict to be used as the globals
1088 when executing examples; by default, use m.__dict__. A copy of this
1089 dict is actually used for each docstring, so that each docstring's
1090 examples start with a clean slate.
1091
1092 Optional keyword arg "verbose" prints lots of stuff if true, prints
1093 only failures if false; by default, it's true iff "-v" is in sys.argv.
1094
1095 Optional keyword arg "isprivate" specifies a function used to
1096 determine whether a name is private. The default function is
1097 doctest.is_private; see its docs for details.
1098
1099 Optional keyword arg "report" prints a summary at the end when true,
1100 else prints nothing at the end. In verbose mode, the summary is
1101 detailed, else very brief (in fact, empty if all tests passed).
1102
Tim Peters6ebe61f2003-06-27 20:48:05 +00001103 Optional keyword arg "optionflags" or's together module constants,
1104 and defaults to 0. This is new in 2.3. Possible values:
1105
1106 DONT_ACCEPT_TRUE_FOR_1
1107 By default, if an expected output block contains just "1",
1108 an actual output block containing just "True" is considered
1109 to be a match, and similarly for "0" versus "False". When
1110 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1111 is allowed.
1112
Tim Peters8a7d2d52001-01-16 07:10:57 +00001113 Advanced tomfoolery: testmod runs methods of a local instance of
1114 class doctest.Tester, then merges the results into (or creates)
1115 global Tester instance doctest.master. Methods of doctest.master
1116 can be called directly too, if you want to do something unusual.
1117 Passing report=0 to testmod is especially useful then, to delay
1118 displaying a summary. Invoke doctest.master.summarize(verbose)
1119 when you're done fiddling.
1120 """
1121
1122 global master
1123
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001124 if m is None:
1125 import sys
1126 # DWA - m will still be None if this wasn't invoked from the command
1127 # line, in which case the following TypeError is about as good an error
1128 # as we should expect
1129 m = sys.modules.get('__main__')
1130
Tim Peters7402f792001-10-02 03:53:41 +00001131 if not _ismodule(m):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001132 raise TypeError("testmod: module required; " + `m`)
1133 if name is None:
1134 name = m.__name__
Tim Peters6ebe61f2003-06-27 20:48:05 +00001135 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
1136 optionflags=optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001137 failures, tries = tester.rundoc(m, name)
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001138 f, t = tester.rundict(m.__dict__, name, m)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001139 failures += f
1140 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001141 if hasattr(m, "__test__"):
1142 testdict = m.__test__
1143 if testdict:
1144 if not hasattr(testdict, "items"):
1145 raise TypeError("testmod: module.__test__ must support "
1146 ".items(); " + `testdict`)
1147 f, t = tester.run__test__(testdict, name + ".__test__")
Tim Peters6ebe61f2003-06-27 20:48:05 +00001148 failures += f
1149 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001150 if report:
1151 tester.summarize()
1152 if master is None:
1153 master = tester
1154 else:
1155 master.merge(tester)
1156 return failures, tries
1157
Tim Petersdb3756d2003-06-29 05:30:48 +00001158###########################################################################
1159# Various doctest extensions, to make using doctest with unittest
1160# easier, and to help debugging when a doctest goes wrong. Original
1161# code by Jim Fulton.
1162
1163# Utilities.
1164
1165# If module is None, return the calling module (the module that called
1166# the routine that called _normalize_module -- this normally won't be
1167# doctest!). If module is a string, it should be the (possibly dotted)
1168# name of a module, and the (rightmost) module object is returned. Else
1169# module is returned untouched; the intent appears to be that module is
1170# already a module object in this case (although this isn't checked).
1171
1172def _normalize_module(module):
1173 import sys
1174
1175 if module is None:
1176 # Get our caller's caller's module.
1177 module = sys._getframe(2).f_globals['__name__']
1178 module = sys.modules[module]
1179
1180 elif isinstance(module, (str, unicode)):
1181 # The ["*"] at the end is a mostly meaningless incantation with
1182 # a crucial property: if, e.g., module is 'a.b.c', it convinces
1183 # __import__ to return c instead of a.
1184 module = __import__(module, globals(), locals(), ["*"])
1185
1186 return module
1187
1188# tests is a list of (testname, docstring, filename, lineno) tuples.
1189# If object has a __doc__ attr, and the __doc__ attr looks like it
1190# contains a doctest (specifically, if it contains an instance of '>>>'),
1191# then tuple
1192# prefix + name, object.__doc__, filename, lineno
1193# is appended to tests. Else tests is left alone.
1194# There is no return value.
1195
1196def _get_doctest(name, object, tests, prefix, filename='', lineno=''):
1197 doc = getattr(object, '__doc__', '')
1198 if isinstance(doc, basestring) and '>>>' in doc:
1199 tests.append((prefix + name, doc, filename, lineno))
1200
1201# tests is a list of (testname, docstring, filename, lineno) tuples.
1202# docstrings containing doctests are appended to tests (if any are found).
1203# items is a dict, like a module or class dict, mapping strings to objects.
1204# mdict is the global dict of a "home" module -- only objects belonging
1205# to this module are searched for docstrings. module is the module to
1206# which mdict belongs.
1207# prefix is a string to be prepended to an object's name when adding a
1208# tuple to tests.
1209# The objects (values) in items are examined (recursively), and doctests
1210# belonging to functions and classes in the home module are appended to
1211# tests.
1212# minlineno is a gimmick to try to guess the file-relative line number
1213# at which a doctest probably begins.
1214
1215def _extract_doctests(items, module, mdict, tests, prefix, minlineno=0):
1216
1217 for name, object in items:
1218 # Only interested in named objects.
1219 if not hasattr(object, '__name__'):
1220 continue
1221
1222 elif hasattr(object, 'func_globals'):
1223 # Looks like a function.
1224 if object.func_globals is not mdict:
1225 # Non-local function.
1226 continue
1227 code = getattr(object, 'func_code', None)
1228 filename = getattr(code, 'co_filename', '')
1229 lineno = getattr(code, 'co_firstlineno', -1) + 1
1230 if minlineno:
1231 minlineno = min(lineno, minlineno)
1232 else:
1233 minlineno = lineno
1234 _get_doctest(name, object, tests, prefix, filename, lineno)
1235
1236 elif hasattr(object, "__module__"):
1237 # Maybe a class-like thing, in which case we care.
1238 if object.__module__ != module.__name__:
1239 # Not the same module.
1240 continue
1241 if not (hasattr(object, '__dict__')
1242 and hasattr(object, '__bases__')):
1243 # Not a class.
1244 continue
1245
1246 lineno = _extract_doctests(object.__dict__.items(),
1247 module,
1248 mdict,
1249 tests,
1250 prefix + name + ".")
1251 # XXX "-3" is unclear.
1252 _get_doctest(name, object, tests, prefix,
1253 lineno="%s (or above)" % (lineno - 3))
1254
1255 return minlineno
1256
1257# Find all the doctests belonging to the module object.
1258# Return a list of
1259# (testname, docstring, filename, lineno)
1260# tuples.
1261
1262def _find_tests(module, prefix=None):
1263 if prefix is None:
1264 prefix = module.__name__
1265 mdict = module.__dict__
1266 tests = []
1267 # Get the module-level doctest (if any).
1268 _get_doctest(prefix, module, tests, '', lineno="1 (or above)")
1269 # Recursively search the module __dict__ for doctests.
1270 if prefix:
1271 prefix += "."
1272 _extract_doctests(mdict.items(), module, mdict, tests, prefix)
1273 return tests
1274
1275# unittest helpers.
1276
1277# A function passed to unittest, for unittest to drive.
1278# tester is doctest Tester instance. doc is the docstring whose
1279# doctests are to be run.
1280
1281def _utest(tester, name, doc, filename, lineno):
1282 import sys
1283 from StringIO import StringIO
1284
1285 old = sys.stdout
1286 sys.stdout = new = StringIO()
1287 try:
1288 failures, tries = tester.runstring(doc, name)
1289 finally:
1290 sys.stdout = old
1291
1292 if failures:
1293 msg = new.getvalue()
1294 lname = '.'.join(name.split('.')[-1:])
1295 if not lineno:
1296 lineno = "0 (don't know line number)"
1297 # Don't change this format! It was designed so that Emacs can
1298 # parse it naturally.
1299 raise DocTestTestFailure('Failed doctest test for %s\n'
1300 ' File "%s", line %s, in %s\n\n%s' %
1301 (name, filename, lineno, lname, msg))
1302
1303class DocTestTestFailure(Exception):
1304 """A doctest test failed"""
1305
1306def DocTestSuite(module=None):
1307 """Convert doctest tests for a module to a unittest TestSuite.
1308
1309 The returned TestSuite is to be run by the unittest framework, and
1310 runs each doctest in the module. If any of the doctests fail,
1311 then the synthesized unit test fails, and an error is raised showing
1312 the name of the file containing the test and a (sometimes approximate)
1313 line number.
1314
1315 The optional module argument provides the module to be tested. It
1316 can be a module object or a (possibly dotted) module name. If not
1317 specified, the module calling DocTestSuite() is used.
1318
1319 Example (although note that unittest supplies many ways to use the
1320 TestSuite returned; see the unittest docs):
1321
1322 import unittest
1323 import doctest
1324 import my_module_with_doctests
1325
1326 suite = doctest.DocTestSuite(my_module_with_doctests)
1327 runner = unittest.TextTestRunner()
1328 runner.run(suite)
1329 """
1330
1331 import unittest
1332
1333 module = _normalize_module(module)
1334 tests = _find_tests(module)
1335 if not tests:
1336 raise ValueError(module, "has no tests")
1337
1338 tests.sort()
1339 suite = unittest.TestSuite()
1340 tester = Tester(module)
1341 for name, doc, filename, lineno in tests:
1342 if not filename:
1343 filename = module.__file__
1344 if filename.endswith(".pyc"):
1345 filename = filename[:-1]
1346 elif filename.endswith(".pyo"):
1347 filename = filename[:-1]
1348 def runit(name=name, doc=doc, filename=filename, lineno=lineno):
1349 _utest(tester, name, doc, filename, lineno)
1350 suite.addTest(unittest.FunctionTestCase(
1351 runit,
1352 description="doctest of " + name))
1353 return suite
1354
1355# Debugging support.
1356
1357def _expect(expect):
1358 # Return the expected output (if any), formatted as a Python
1359 # comment block.
1360 if expect:
1361 expect = "\n# ".join(expect.split("\n"))
1362 expect = "\n# Expect:\n# %s" % expect
1363 return expect
1364
1365def testsource(module, name):
1366 """Extract the doctest examples from a docstring.
1367
1368 Provide the module (or dotted name of the module) containing the
1369 tests to be extracted, and the name (within the module) of the object
1370 with the docstring containing the tests to be extracted.
1371
1372 The doctest examples are returned as a string containing Python
1373 code. The expected output blocks in the examples are converted
1374 to Python comments.
1375 """
1376
1377 module = _normalize_module(module)
1378 tests = _find_tests(module, "")
1379 test = [doc for (tname, doc, dummy, dummy) in tests
1380 if tname == name]
1381 if not test:
1382 raise ValueError(name, "not found in tests")
1383 test = test[0]
1384 examples = [source + _expect(expect)
1385 for source, expect, dummy in _extract_examples(test)]
1386 return '\n'.join(examples)
1387
1388def debug(module, name):
1389 """Debug a single docstring containing doctests.
1390
1391 Provide the module (or dotted name of the module) containing the
1392 docstring to be debugged, and the name (within the module) of the
1393 object with the docstring to be debugged.
1394
1395 The doctest examples are extracted (see function testsource()),
1396 and written to a temp file. The Python debugger (pdb) is then
1397 invoked on that file.
1398 """
1399
1400 import os
1401 import pdb
1402 import tempfile
1403
1404 module = _normalize_module(module)
1405 testsrc = testsource(module, name)
1406 srcfilename = tempfile.mktemp("doctestdebug.py")
1407 f = file(srcfilename, 'w')
1408 f.write(testsrc)
1409 f.close()
1410
1411 globs = {}
1412 globs.update(module.__dict__)
1413 try:
1414 # Note that %r is vital here. '%s' instead can, e.g., cause
1415 # backslashes to get treated as metacharacters on Windows.
1416 pdb.run("execfile(%r)" % srcfilename, globs, globs)
1417 finally:
1418 os.remove(srcfilename)
1419
1420
1421
Tim Peters8a7d2d52001-01-16 07:10:57 +00001422class _TestClass:
1423 """
1424 A pointless class, for sanity-checking of docstring testing.
1425
1426 Methods:
1427 square()
1428 get()
1429
1430 >>> _TestClass(13).get() + _TestClass(-12).get()
1431 1
1432 >>> hex(_TestClass(13).square().get())
1433 '0xa9'
1434 """
1435
1436 def __init__(self, val):
1437 """val -> _TestClass object with associated value val.
1438
1439 >>> t = _TestClass(123)
1440 >>> print t.get()
1441 123
1442 """
1443
1444 self.val = val
1445
1446 def square(self):
1447 """square() -> square TestClass's associated value
1448
1449 >>> _TestClass(13).square().get()
1450 169
1451 """
1452
1453 self.val = self.val ** 2
1454 return self
1455
1456 def get(self):
1457 """get() -> return TestClass's associated value.
1458
1459 >>> x = _TestClass(-42)
1460 >>> print x.get()
1461 -42
1462 """
1463
1464 return self.val
1465
1466__test__ = {"_TestClass": _TestClass,
1467 "string": r"""
1468 Example of a string object, searched as-is.
1469 >>> x = 1; y = 2
1470 >>> x + y, x * y
1471 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001472 """,
1473 "bool-int equivalence": r"""
1474 In 2.2, boolean expressions displayed
1475 0 or 1. By default, we still accept
1476 them. This can be disabled by passing
1477 DONT_ACCEPT_TRUE_FOR_1 to the new
1478 optionflags argument.
1479 >>> 4 == 4
1480 1
1481 >>> 4 == 4
1482 True
1483 >>> 4 > 4
1484 0
1485 >>> 4 > 4
1486 False
1487 """,
Tim Peters8a7d2d52001-01-16 07:10:57 +00001488 }
1489
1490def _test():
1491 import doctest
1492 return doctest.testmod(doctest)
1493
1494if __name__ == "__main__":
1495 _test()