blob: dcee8599702b24301c8e457ce70fa8237d6011de [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8a7d2d52001-01-16 07:10:57 +00002# Released to the public domain 16-Jan-2001,
3# by Tim Peters (tim.one@home.com).
4
5# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
6
7"""Module doctest -- a framework for running examples in docstrings.
8
9NORMAL USAGE
10
11In normal use, end each module M with:
12
13def _test():
14 import doctest, M # replace M with your module's name
15 return doctest.testmod(M) # ditto
16
17if __name__ == "__main__":
18 _test()
19
20Then running the module as a script will cause the examples in the
21docstrings to get executed and verified:
22
23python M.py
24
25This won't display anything unless an example fails, in which case the
26failing example(s) and the cause(s) of the failure(s) are printed to stdout
27(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
28line of output is "Test failed.".
29
30Run it with the -v switch instead:
31
32python M.py -v
33
34and a detailed report of all examples tried is printed to stdout, along
35with assorted summaries at the end.
36
37You can force verbose mode by passing "verbose=1" to testmod, or prohibit
38it by passing "verbose=0". In either of those cases, sys.argv is not
39examined by testmod.
40
41In any case, testmod returns a 2-tuple of ints (f, t), where f is the
42number of docstring examples that failed and t is the total number of
43docstring examples attempted.
44
45
46WHICH DOCSTRINGS ARE EXAMINED?
47
48+ M.__doc__.
49
50+ f.__doc__ for all functions f in M.__dict__.values(), except those
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000051 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000052
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000053+ C.__doc__ for all classes C in M.__dict__.values(), except those
54 defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000055
56+ If M.__test__ exists and "is true", it must be a dict, and
57 each entry maps a (string) name to a function object, class object, or
58 string. Function and class object docstrings found from M.__test__
59 are searched even if the name is private, and strings are searched
60 directly as if they were docstrings. In output, a key K in M.__test__
61 appears with name
62 <name of M>.__test__.K
63
64Any classes found are recursively searched similarly, to test docstrings in
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000065their contained methods and nested classes. All names reached from
66M.__test__ are searched.
Tim Peters8a7d2d52001-01-16 07:10:57 +000067
Raymond Hettinger71adf7e2003-07-16 19:25:22 +000068Optionally, functions with private names can be skipped (unless listed in
69M.__test__) by supplying a function to the "isprivate" argument that will
70identify private functions. For convenience, one such function is
71supplied. docttest.is_private considers a name to be private if it begins
72with an underscore (like "_my_func") but doesn't both begin and end with
73(at least) two underscores (like "__init__"). By supplying this function
74or your own "isprivate" function to testmod, the behavior can be customized.
Tim Peters8a7d2d52001-01-16 07:10:57 +000075
76If you want to test docstrings in objects with private names too, stuff
77them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
78own isprivate function to Tester's constructor, or call the rundoc method
79of a Tester instance).
80
Tim Peters8a7d2d52001-01-16 07:10:57 +000081WHAT'S THE EXECUTION CONTEXT?
82
83By default, each time testmod finds a docstring to test, it uses a *copy*
84of M's globals (so that running tests on a module doesn't change the
85module's real globals, and so that one test in M can't leave behind crumbs
86that accidentally allow another test to work). This means examples can
87freely use any names defined at top-level in M. It also means that sloppy
88imports (see above) can cause examples in external docstrings to use
89globals inappropriate for them.
90
91You can force use of your own dict as the execution context by passing
92"globs=your_dict" to testmod instead. Presumably this would be a copy of
93M.__dict__ merged with the globals from other imported modules.
94
95
96WHAT IF I WANT TO TEST A WHOLE PACKAGE?
97
98Piece o' cake, provided the modules do their testing from docstrings.
99Here's the test.py I use for the world's most elaborate Rational/
100floating-base-conversion pkg (which I'll distribute some day):
101
102from Rational import Cvt
103from Rational import Format
104from Rational import machprec
105from Rational import Rat
106from Rational import Round
107from Rational import utils
108
109modules = (Cvt,
110 Format,
111 machprec,
112 Rat,
113 Round,
114 utils)
115
116def _test():
117 import doctest
118 import sys
119 verbose = "-v" in sys.argv
120 for mod in modules:
121 doctest.testmod(mod, verbose=verbose, report=0)
122 doctest.master.summarize()
123
124if __name__ == "__main__":
125 _test()
126
127IOW, it just runs testmod on all the pkg modules. testmod remembers the
128names and outcomes (# of failures, # of tries) for each item it's seen, and
129passing "report=0" prevents it from printing a summary in verbose mode.
130Instead, the summary is delayed until all modules have been tested, and
131then "doctest.master.summarize()" forces the summary at the end.
132
133So this is very nice in practice: each module can be tested individually
134with almost no work beyond writing up docstring examples, and collections
135of modules can be tested too as a unit with no more work than the above.
136
137
138WHAT ABOUT EXCEPTIONS?
139
140No problem, as long as the only output generated by the example is the
141traceback itself. For example:
142
Tim Peters60e23f42001-02-14 00:43:21 +0000143 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +0000144 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000145 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000146 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000147 >>>
148
149Note that only the exception type and value are compared (specifically,
150only the last line in the traceback).
151
152
153ADVANCED USAGE
154
155doctest.testmod() captures the testing policy I find most useful most
156often. You may want other policies.
157
158testmod() actually creates a local instance of class doctest.Tester, runs
159appropriate methods of that class, and merges the results into global
160Tester instance doctest.master.
161
162You can create your own instances of doctest.Tester, and so build your own
163policies, or even run methods of doctest.master directly. See
164doctest.Tester.__doc__ for details.
165
166
167SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
168
169Oh ya. It's easy! In most cases a copy-and-paste of an interactive
170console session works fine -- just make sure the leading whitespace is
171rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
172right, but doctest is not in the business of guessing what you think a tab
173means).
174
175 >>> # comments are ignored
176 >>> x = 12
177 >>> x
178 12
179 >>> if x == 13:
180 ... print "yes"
181 ... else:
182 ... print "no"
183 ... print "NO"
184 ... print "NO!!!"
185 ...
186 no
187 NO
188 NO!!!
189 >>>
190
191Any expected output must immediately follow the final ">>>" or "..." line
192containing the code, and the expected output (if any) extends to the next
193">>>" or all-whitespace line. That's it.
194
195Bummers:
196
197+ Expected output cannot contain an all-whitespace line, since such a line
198 is taken to signal the end of expected output.
199
200+ Output to stdout is captured, but not output to stderr (exception
201 tracebacks are captured via a different means).
202
203+ If you continue a line via backslashing in an interactive session, or for
204 any other reason use a backslash, you need to double the backslash in the
205 docstring version. This is simply because you're in a string, and so the
206 backslash must be escaped for it to survive intact. Like:
207
208>>> if "yes" == \\
209... "y" + \\
210... "es": # in the source code you'll see the doubled backslashes
211... print 'yes'
212yes
213
214The starting column doesn't matter:
215
216>>> assert "Easy!"
217 >>> import math
218 >>> math.floor(1.9)
219 1.0
220
221and as many leading whitespace characters are stripped from the expected
222output as appeared in the initial ">>>" line that triggered it.
223
224If you execute this very file, the examples above will be found and
225executed, leading to this output in verbose mode:
226
227Running doctest.__doc__
Tim Peters60e23f42001-02-14 00:43:21 +0000228Trying: [1, 2, 3].remove(42)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000229Expecting:
Tim Petersea4f9312001-02-13 20:54:42 +0000230Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000231 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000232ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000233ok
234Trying: x = 12
235Expecting: nothing
236ok
237Trying: x
238Expecting: 12
239ok
240Trying:
241if x == 13:
242 print "yes"
243else:
244 print "no"
245 print "NO"
246 print "NO!!!"
247Expecting:
248no
249NO
250NO!!!
251ok
252... and a bunch more like that, with this summary at the end:
253
2545 items had no tests:
255 doctest.Tester.__init__
256 doctest.Tester.run__test__
257 doctest.Tester.summarize
258 doctest.run_docstring_examples
259 doctest.testmod
26012 items passed all tests:
261 8 tests in doctest
262 6 tests in doctest.Tester
263 10 tests in doctest.Tester.merge
Tim Peters17111f32001-10-03 04:08:26 +0000264 14 tests in doctest.Tester.rundict
Tim Peters8a7d2d52001-01-16 07:10:57 +0000265 3 tests in doctest.Tester.rundoc
266 3 tests in doctest.Tester.runstring
267 2 tests in doctest.__test__._TestClass
268 2 tests in doctest.__test__._TestClass.__init__
269 2 tests in doctest.__test__._TestClass.get
270 1 tests in doctest.__test__._TestClass.square
271 2 tests in doctest.__test__.string
272 7 tests in doctest.is_private
Tim Peters17111f32001-10-03 04:08:26 +000027360 tests in 17 items.
27460 passed and 0 failed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000275Test passed.
276"""
277
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000278__all__ = [
279 'testmod',
280 'run_docstring_examples',
281 'is_private',
282 'Tester',
Tim Petersdb3756d2003-06-29 05:30:48 +0000283 'DocTestTestFailure',
284 'DocTestSuite',
285 'testsource',
286 'debug',
Raymond Hettingercc39a132003-07-11 22:36:52 +0000287 'master',
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000288]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000289
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000290import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000291
Tim Peters8a7d2d52001-01-16 07:10:57 +0000292import re
293PS1 = ">>>"
294PS2 = "..."
295_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
296_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
297_isEmpty = re.compile(r"\s*$").match
298_isComment = re.compile(r"\s*#").match
299del re
300
Tim Peters7402f792001-10-02 03:53:41 +0000301from types import StringTypes as _StringTypes
302
303from inspect import isclass as _isclass
304from inspect import isfunction as _isfunction
305from inspect import ismodule as _ismodule
Tim Peters17111f32001-10-03 04:08:26 +0000306from inspect import classify_class_attrs as _classify_class_attrs
Tim Peters7402f792001-10-02 03:53:41 +0000307
Tim Peters6ebe61f2003-06-27 20:48:05 +0000308# Option constants.
309DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
310
Tim Peters8a7d2d52001-01-16 07:10:57 +0000311# Extract interactive examples from a string. Return a list of triples,
312# (source, outcome, lineno). "source" is the source code, and ends
313# with a newline iff the source spans more than one line. "outcome" is
314# the expected output if any, else an empty string. When not empty,
315# outcome always ends with a newline. "lineno" is the line number,
316# 0-based wrt the start of the string, of the first source line.
317
318def _extract_examples(s):
319 isPS1, isPS2 = _isPS1, _isPS2
320 isEmpty, isComment = _isEmpty, _isComment
321 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000322 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000323 i, n = 0, len(lines)
324 while i < n:
325 line = lines[i]
326 i = i + 1
327 m = isPS1(line)
328 if m is None:
329 continue
330 j = m.end(0) # beyond the prompt
331 if isEmpty(line, j) or isComment(line, j):
332 # a bare prompt or comment -- not interesting
333 continue
334 lineno = i - 1
335 if line[j] != " ":
336 raise ValueError("line " + `lineno` + " of docstring lacks "
337 "blank after " + PS1 + ": " + line)
338 j = j + 1
339 blanks = m.group(1)
340 nblanks = len(blanks)
341 # suck up this and following PS2 lines
342 source = []
343 while 1:
344 source.append(line[j:])
345 line = lines[i]
346 m = isPS2(line)
347 if m:
348 if m.group(1) != blanks:
349 raise ValueError("inconsistent leading whitespace "
350 "in line " + `i` + " of docstring: " + line)
351 i = i + 1
352 else:
353 break
354 if len(source) == 1:
355 source = source[0]
356 else:
357 # get rid of useless null line from trailing empty "..."
358 if source[-1] == "":
359 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000360 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000361 # suck up response
362 if isPS1(line) or isEmpty(line):
363 expect = ""
364 else:
365 expect = []
366 while 1:
367 if line[:nblanks] != blanks:
368 raise ValueError("inconsistent leading whitespace "
369 "in line " + `i` + " of docstring: " + line)
370 expect.append(line[nblanks:])
371 i = i + 1
372 line = lines[i]
373 if isPS1(line) or isEmpty(line):
374 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000375 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000376 examples.append( (source, expect, lineno) )
377 return examples
378
379# Capture stdout when running examples.
380
381class _SpoofOut:
382 def __init__(self):
383 self.clear()
384 def write(self, s):
385 self.buf.append(s)
386 def get(self):
Tim Petersf9bb4962001-02-14 06:35:35 +0000387 guts = "".join(self.buf)
388 # If anything at all was written, make sure there's a trailing
389 # newline. There's no way for the expected output to indicate
390 # that a trailing newline is missing.
391 if guts and not guts.endswith("\n"):
392 guts = guts + "\n"
Tim Petersc77db342001-10-23 02:21:52 +0000393 # Prevent softspace from screwing up the next test case, in
394 # case they used print with a trailing comma in an example.
395 if hasattr(self, "softspace"):
396 del self.softspace
Tim Petersf9bb4962001-02-14 06:35:35 +0000397 return guts
Tim Peters8a7d2d52001-01-16 07:10:57 +0000398 def clear(self):
399 self.buf = []
Tim Petersc77db342001-10-23 02:21:52 +0000400 if hasattr(self, "softspace"):
401 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000402 def flush(self):
403 # JPython calls flush
404 pass
405
406# Display some tag-and-msg pairs nicely, keeping the tag and its msg
407# on the same line when that makes sense.
408
409def _tag_out(printer, *tag_msg_pairs):
410 for tag, msg in tag_msg_pairs:
411 printer(tag + ":")
412 msg_has_nl = msg[-1:] == "\n"
413 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000414 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000415 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
416 printer(" ")
417 else:
418 printer("\n")
419 printer(msg)
420 if not msg_has_nl:
421 printer("\n")
422
423# Run list of examples, in context globs. "out" can be used to display
424# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
425# that captures the examples' std output. Return (#failures, #tries).
426
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000427def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000428 compileflags, optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000429 import sys, traceback
430 OK, BOOM, FAIL = range(3)
431 NADA = "nothing"
432 stderr = _SpoofOut()
433 failures = 0
434 for source, want, lineno in examples:
435 if verbose:
436 _tag_out(out, ("Trying", source),
437 ("Expecting", want or NADA))
438 fakeout.clear()
439 try:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000440 exec compile(source, "<string>", "single",
441 compileflags, 1) in globs
Tim Peters8a7d2d52001-01-16 07:10:57 +0000442 got = fakeout.get()
443 state = OK
Tim Petersbcc2c122002-03-20 19:32:03 +0000444 except KeyboardInterrupt:
445 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000446 except:
447 # See whether the exception was expected.
Tim Petersea4f9312001-02-13 20:54:42 +0000448 if want.find("Traceback (innermost last):\n") == 0 or \
449 want.find("Traceback (most recent call last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000450 # Only compare exception type and value - the rest of
451 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000452 want = want.split('\n')[-2] + '\n'
Tim Peters77f2d502001-06-24 18:59:01 +0000453 exc_type, exc_val = sys.exc_info()[:2]
Tim Peters08bba952001-06-24 06:46:58 +0000454 got = traceback.format_exception_only(exc_type, exc_val)[-1]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000455 state = OK
456 else:
457 # unexpected exception
458 stderr.clear()
459 traceback.print_exc(file=stderr)
460 state = BOOM
461
462 if state == OK:
Tim Peters6ebe61f2003-06-27 20:48:05 +0000463 if (got == want or
464 (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and
465 (got, want) in (("True\n", "1\n"), ("False\n", "0\n"))
466 )
467 ):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000468 if verbose:
469 out("ok\n")
470 continue
471 state = FAIL
472
473 assert state in (FAIL, BOOM)
474 failures = failures + 1
475 out("*" * 65 + "\n")
476 _tag_out(out, ("Failure in example", source))
477 out("from line #" + `lineno` + " of " + name + "\n")
478 if state == FAIL:
479 _tag_out(out, ("Expected", want or NADA), ("Got", got))
480 else:
481 assert state == BOOM
482 _tag_out(out, ("Exception raised", stderr.get()))
483
484 return failures, len(examples)
485
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000486# Get the future-flags associated with the future features that have been
487# imported into globs.
488
489def _extract_future_flags(globs):
490 flags = 0
491 for fname in __future__.all_feature_names:
492 feature = globs.get(fname, None)
493 if feature is getattr(__future__, fname):
494 flags |= feature.compiler_flag
495 return flags
496
Tim Petersd4ad59e2001-06-24 20:02:47 +0000497# Run list of examples, in a shallow copy of context (dict) globs.
498# Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000499
Tim Peters6ebe61f2003-06-27 20:48:05 +0000500def _run_examples(examples, globs, verbose, name, compileflags,
501 optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000502 import sys
503 saveout = sys.stdout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000504 globs = globs.copy()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000505 try:
506 sys.stdout = fakeout = _SpoofOut()
507 x = _run_examples_inner(saveout.write, fakeout, examples,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000508 globs, verbose, name, compileflags,
509 optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000510 finally:
511 sys.stdout = saveout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000512 # While Python gc can clean up most cycles on its own, it doesn't
513 # chase frame objects. This is especially irksome when running
514 # generator tests that raise exceptions, because a named generator-
515 # iterator gets an entry in globs, and the generator-iterator
516 # object's frame's traceback info points back to globs. This is
Tim Petersfee69d02001-06-24 20:24:16 +0000517 # easy to break just by clearing the namespace. This can also
518 # help to break other kinds of cycles, and even for cycles that
519 # gc can break itself it's better to break them ASAP.
Tim Petersd4ad59e2001-06-24 20:02:47 +0000520 globs.clear()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000521 return x
522
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000523def run_docstring_examples(f, globs, verbose=0, name="NoName",
Tim Peters6ebe61f2003-06-27 20:48:05 +0000524 compileflags=None, optionflags=0):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000525 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
526
Tim Petersd4ad59e2001-06-24 20:02:47 +0000527 Use (a shallow copy of) dict globs as the globals for execution.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000528 Return (#failures, #tries).
529
530 If optional arg verbose is true, print stuff even if there are no
531 failures.
532 Use string name in failure msgs.
533 """
534
535 try:
536 doc = f.__doc__
537 if not doc:
538 # docstring empty or None
539 return 0, 0
540 # just in case CT invents a doc object that has to be forced
541 # to look like a string <0.9 wink>
542 doc = str(doc)
Tim Petersbcc2c122002-03-20 19:32:03 +0000543 except KeyboardInterrupt:
544 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000545 except:
546 return 0, 0
547
548 e = _extract_examples(doc)
549 if not e:
550 return 0, 0
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000551 if compileflags is None:
552 compileflags = _extract_future_flags(globs)
Tim Peters6ebe61f2003-06-27 20:48:05 +0000553 return _run_examples(e, globs, verbose, name, compileflags, optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000554
555def is_private(prefix, base):
556 """prefix, base -> true iff name prefix + "." + base is "private".
557
558 Prefix may be an empty string, and base does not contain a period.
559 Prefix is ignored (although functions you write conforming to this
560 protocol may make use of it).
561 Return true iff base begins with an (at least one) underscore, but
562 does not both begin and end with (at least) two underscores.
563
564 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000565 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000566 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000567 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000568 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000569 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000570 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000571 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000572 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000573 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000574 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000575 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000576 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000577 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000578 """
579
580 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
581
Tim Peters7402f792001-10-02 03:53:41 +0000582# Determine if a class of function was defined in the given module.
583
584def _from_module(module, object):
585 if _isfunction(object):
586 return module.__dict__ is object.func_globals
587 if _isclass(object):
588 return module.__name__ == object.__module__
589 raise ValueError("object must be a class or function")
590
Tim Peters8a7d2d52001-01-16 07:10:57 +0000591class Tester:
592 """Class Tester -- runs docstring examples and accumulates stats.
593
594In normal use, function doctest.testmod() hides all this from you,
595so use that if you can. Create your own instances of Tester to do
596fancier things.
597
598Methods:
599 runstring(s, name)
600 Search string s for examples to run; use name for logging.
601 Return (#failures, #tries).
602
603 rundoc(object, name=None)
604 Search object.__doc__ for examples to run; use name (or
605 object.__name__) for logging. Return (#failures, #tries).
606
Tim Peters7402f792001-10-02 03:53:41 +0000607 rundict(d, name, module=None)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000608 Search for examples in docstrings in all of d.values(); use name
Tim Peters7402f792001-10-02 03:53:41 +0000609 for logging. Exclude functions and classes not defined in module
610 if specified. Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000611
612 run__test__(d, name)
613 Treat dict d like module.__test__. Return (#failures, #tries).
614
615 summarize(verbose=None)
616 Display summary of testing results, to stdout. Return
617 (#failures, #tries).
618
619 merge(other)
620 Merge in the test results from Tester instance "other".
621
622>>> from doctest import Tester
623>>> t = Tester(globs={'x': 42}, verbose=0)
624>>> t.runstring(r'''
625... >>> x = x * 2
626... >>> print x
627... 42
628... ''', 'XYZ')
629*****************************************************************
630Failure in example: print x
631from line #2 of XYZ
632Expected: 42
633Got: 84
634(1, 2)
635>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
636(0, 2)
637>>> t.summarize()
Guido van Rossum261d91a2001-03-18 17:05:58 +0000638*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006391 items had failures:
640 1 of 2 in XYZ
641***Test Failed*** 1 failures.
642(1, 4)
643>>> t.summarize(verbose=1)
6441 items passed all tests:
645 2 tests in example2
Guido van Rossum261d91a2001-03-18 17:05:58 +0000646*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006471 items had failures:
648 1 of 2 in XYZ
6494 tests in 2 items.
6503 passed and 1 failed.
651***Test Failed*** 1 failures.
652(1, 4)
653>>>
654"""
655
656 def __init__(self, mod=None, globs=None, verbose=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000657 isprivate=None, optionflags=0):
658 """mod=None, globs=None, verbose=None, isprivate=None,
659optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000660
661See doctest.__doc__ for an overview.
662
663Optional keyword arg "mod" is a module, whose globals are used for
664executing examples. If not specified, globs must be specified.
665
666Optional keyword arg "globs" gives a dict to be used as the globals
667when executing examples; if not specified, use the globals from
668module mod.
669
670In either case, a copy of the dict is used for each docstring
671examined.
672
673Optional keyword arg "verbose" prints lots of stuff if true, only
674failures if false; by default, it's true iff "-v" is in sys.argv.
675
676Optional keyword arg "isprivate" specifies a function used to determine
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000677whether a name is private. The default function is to assume that
678no functions are private. The "isprivate" arg may be set to
679doctest.is_private in order to skip over functions marked as private
680using an underscore naming convention; see its docs for details.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000681
682See doctest.testmod docs for the meaning of optionflags.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000683"""
684
685 if mod is None and globs is None:
686 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters7402f792001-10-02 03:53:41 +0000687 if mod is not None and not _ismodule(mod):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000688 raise TypeError("Tester.__init__: mod must be a module; " +
689 `mod`)
690 if globs is None:
691 globs = mod.__dict__
692 self.globs = globs
693
694 if verbose is None:
695 import sys
696 verbose = "-v" in sys.argv
697 self.verbose = verbose
698
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000699 # By default, assume that nothing is private
Tim Peters8a7d2d52001-01-16 07:10:57 +0000700 if isprivate is None:
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000701 isprivate = lambda prefix, base: 0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000702 self.isprivate = isprivate
703
Tim Peters6ebe61f2003-06-27 20:48:05 +0000704 self.optionflags = optionflags
705
Tim Peters8a7d2d52001-01-16 07:10:57 +0000706 self.name2ft = {} # map name to (#failures, #trials) pair
707
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000708 self.compileflags = _extract_future_flags(globs)
709
Tim Peters8a7d2d52001-01-16 07:10:57 +0000710 def runstring(self, s, name):
711 """
712 s, name -> search string s for examples to run, logging as name.
713
714 Use string name as the key for logging the outcome.
715 Return (#failures, #examples).
716
717 >>> t = Tester(globs={}, verbose=1)
718 >>> test = r'''
719 ... # just an example
720 ... >>> x = 1 + 2
721 ... >>> x
722 ... 3
723 ... '''
724 >>> t.runstring(test, "Example")
725 Running string Example
726 Trying: x = 1 + 2
727 Expecting: nothing
728 ok
729 Trying: x
730 Expecting: 3
731 ok
732 0 of 2 examples failed in string Example
733 (0, 2)
734 """
735
736 if self.verbose:
737 print "Running string", name
738 f = t = 0
739 e = _extract_examples(s)
740 if e:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000741 f, t = _run_examples(e, self.globs, self.verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000742 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000743 if self.verbose:
744 print f, "of", t, "examples failed in string", name
745 self.__record_outcome(name, f, t)
746 return f, t
747
748 def rundoc(self, object, name=None):
749 """
750 object, name=None -> search object.__doc__ for examples to run.
751
752 Use optional string name as the key for logging the outcome;
753 by default use object.__name__.
754 Return (#failures, #examples).
755 If object is a class object, search recursively for method
756 docstrings too.
757 object.__doc__ is examined regardless of name, but if object is
758 a class, whether private names reached from object are searched
759 depends on the constructor's "isprivate" argument.
760
761 >>> t = Tester(globs={}, verbose=0)
762 >>> def _f():
763 ... '''Trivial docstring example.
764 ... >>> assert 2 == 2
765 ... '''
766 ... return 32
767 ...
768 >>> t.rundoc(_f) # expect 0 failures in 1 example
769 (0, 1)
770 """
771
772 if name is None:
773 try:
774 name = object.__name__
775 except AttributeError:
776 raise ValueError("Tester.rundoc: name must be given "
777 "when object.__name__ doesn't exist; " + `object`)
778 if self.verbose:
779 print "Running", name + ".__doc__"
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000780 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
Tim Peters275abbd2003-06-29 03:11:20 +0000781 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000782 if self.verbose:
783 print f, "of", t, "examples failed in", name + ".__doc__"
784 self.__record_outcome(name, f, t)
Tim Peters7402f792001-10-02 03:53:41 +0000785 if _isclass(object):
Tim Peters17111f32001-10-03 04:08:26 +0000786 # In 2.2, class and static methods complicate life. Build
787 # a dict "that works", by hook or by crook.
788 d = {}
789 for tag, kind, homecls, value in _classify_class_attrs(object):
790
791 if homecls is not object:
792 # Only look at names defined immediately by the class.
793 continue
794
795 elif self.isprivate(name, tag):
796 continue
797
798 elif kind == "method":
799 # value is already a function
800 d[tag] = value
801
802 elif kind == "static method":
803 # value isn't a function, but getattr reveals one
804 d[tag] = getattr(object, tag)
805
806 elif kind == "class method":
807 # Hmm. A classmethod object doesn't seem to reveal
808 # enough. But getattr turns it into a bound method,
809 # and from there .im_func retrieves the underlying
810 # function.
811 d[tag] = getattr(object, tag).im_func
812
813 elif kind == "property":
814 # The methods implementing the property have their
815 # own docstrings -- but the property may have one too.
816 if value.__doc__ is not None:
817 d[tag] = str(value.__doc__)
818
819 elif kind == "data":
820 # Grab nested classes.
821 if _isclass(value):
822 d[tag] = value
823
824 else:
825 raise ValueError("teach doctest about %r" % kind)
826
827 f2, t2 = self.run__test__(d, name)
828 f += f2
829 t += t2
830
Tim Peters8a7d2d52001-01-16 07:10:57 +0000831 return f, t
832
Tim Peters7402f792001-10-02 03:53:41 +0000833 def rundict(self, d, name, module=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000834 """
Tim Peters7402f792001-10-02 03:53:41 +0000835 d, name, module=None -> search for docstring examples in d.values().
Tim Peters8a7d2d52001-01-16 07:10:57 +0000836
837 For k, v in d.items() such that v is a function or class,
838 do self.rundoc(v, name + "." + k). Whether this includes
839 objects with private names depends on the constructor's
Tim Peters7402f792001-10-02 03:53:41 +0000840 "isprivate" argument. If module is specified, functions and
841 classes that are not defined in module are excluded.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000842 Return aggregate (#failures, #examples).
843
Tim Peters7402f792001-10-02 03:53:41 +0000844 Build and populate two modules with sample functions to test that
845 exclusion of external functions and classes works.
846
847 >>> import new
848 >>> m1 = new.module('_m1')
849 >>> m2 = new.module('_m2')
850 >>> test_data = \"""
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000851 ... def _f():
Tim Peters7402f792001-10-02 03:53:41 +0000852 ... '''>>> assert 1 == 1
853 ... '''
854 ... def g():
Tim Peters8a7d2d52001-01-16 07:10:57 +0000855 ... '''>>> assert 2 != 1
856 ... '''
Tim Peters7402f792001-10-02 03:53:41 +0000857 ... class H:
858 ... '''>>> assert 2 > 1
859 ... '''
860 ... def bar(self):
861 ... '''>>> assert 1 < 2
862 ... '''
863 ... \"""
864 >>> exec test_data in m1.__dict__
865 >>> exec test_data in m2.__dict__
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000866 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tim Peters7402f792001-10-02 03:53:41 +0000867
868 Tests that objects outside m1 are excluded:
869
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000870 >>> t = Tester(globs={}, verbose=0, isprivate=is_private)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000871 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000872 (0, 3)
873
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000874 Again, but with the default isprivate function allowing _f:
Tim Peters7402f792001-10-02 03:53:41 +0000875
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000876 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000877 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000878 (0, 4)
879
880 And once more, not excluding stuff outside m1:
881
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000882 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000883 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Tim Peters7402f792001-10-02 03:53:41 +0000884 (0, 8)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000885
886 The exclusion of objects from outside the designated module is
887 meant to be invoked automagically by testmod.
888
Raymond Hettinger71adf7e2003-07-16 19:25:22 +0000889 >>> testmod(m1, isprivate=is_private)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000890 (0, 3)
891
Tim Peters8a7d2d52001-01-16 07:10:57 +0000892 """
893
894 if not hasattr(d, "items"):
895 raise TypeError("Tester.rundict: d must support .items(); " +
896 `d`)
897 f = t = 0
Tim Peters24a41912001-03-21 23:07:59 +0000898 # Run the tests by alpha order of names, for consistency in
899 # verbose-mode output.
900 names = d.keys()
901 names.sort()
902 for thisname in names:
903 value = d[thisname]
Tim Peters7402f792001-10-02 03:53:41 +0000904 if _isfunction(value) or _isclass(value):
905 if module and not _from_module(module, value):
906 continue
Tim Peters8a7d2d52001-01-16 07:10:57 +0000907 f2, t2 = self.__runone(value, name + "." + thisname)
908 f = f + f2
909 t = t + t2
910 return f, t
911
912 def run__test__(self, d, name):
913 """d, name -> Treat dict d like module.__test__.
914
915 Return (#failures, #tries).
916 See testmod.__doc__ for details.
917 """
918
919 failures = tries = 0
920 prefix = name + "."
921 savepvt = self.isprivate
922 try:
923 self.isprivate = lambda *args: 0
Tim Peters24a41912001-03-21 23:07:59 +0000924 # Run the tests by alpha order of names, for consistency in
925 # verbose-mode output.
926 keys = d.keys()
927 keys.sort()
928 for k in keys:
929 v = d[k]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000930 thisname = prefix + k
Tim Peters7402f792001-10-02 03:53:41 +0000931 if type(v) in _StringTypes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000932 f, t = self.runstring(v, thisname)
Tim Peters7402f792001-10-02 03:53:41 +0000933 elif _isfunction(v) or _isclass(v):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000934 f, t = self.rundoc(v, thisname)
935 else:
936 raise TypeError("Tester.run__test__: values in "
937 "dict must be strings, functions "
938 "or classes; " + `v`)
939 failures = failures + f
940 tries = tries + t
941 finally:
942 self.isprivate = savepvt
943 return failures, tries
944
945 def summarize(self, verbose=None):
946 """
947 verbose=None -> summarize results, return (#failures, #tests).
948
949 Print summary of test results to stdout.
950 Optional arg 'verbose' controls how wordy this is. By
951 default, use the verbose setting established by the
952 constructor.
953 """
954
955 if verbose is None:
956 verbose = self.verbose
957 notests = []
958 passed = []
959 failed = []
960 totalt = totalf = 0
961 for x in self.name2ft.items():
962 name, (f, t) = x
963 assert f <= t
964 totalt = totalt + t
965 totalf = totalf + f
966 if t == 0:
967 notests.append(name)
968 elif f == 0:
969 passed.append( (name, t) )
970 else:
971 failed.append(x)
972 if verbose:
973 if notests:
974 print len(notests), "items had no tests:"
975 notests.sort()
976 for thing in notests:
977 print " ", thing
978 if passed:
979 print len(passed), "items passed all tests:"
980 passed.sort()
981 for thing, count in passed:
982 print " %3d tests in %s" % (count, thing)
983 if failed:
Guido van Rossumaf00a462001-03-18 16:58:44 +0000984 print "*" * 65
Tim Peters8a7d2d52001-01-16 07:10:57 +0000985 print len(failed), "items had failures:"
986 failed.sort()
987 for thing, (f, t) in failed:
988 print " %3d of %3d in %s" % (f, t, thing)
989 if verbose:
990 print totalt, "tests in", len(self.name2ft), "items."
991 print totalt - totalf, "passed and", totalf, "failed."
992 if totalf:
993 print "***Test Failed***", totalf, "failures."
994 elif verbose:
995 print "Test passed."
996 return totalf, totalt
997
998 def merge(self, other):
999 """
1000 other -> merge in test results from the other Tester instance.
1001
1002 If self and other both have a test result for something
1003 with the same name, the (#failures, #tests) results are
1004 summed, and a warning is printed to stdout.
1005
1006 >>> from doctest import Tester
1007 >>> t1 = Tester(globs={}, verbose=0)
1008 >>> t1.runstring('''
1009 ... >>> x = 12
1010 ... >>> print x
1011 ... 12
1012 ... ''', "t1example")
1013 (0, 2)
1014 >>>
1015 >>> t2 = Tester(globs={}, verbose=0)
1016 >>> t2.runstring('''
1017 ... >>> x = 13
1018 ... >>> print x
1019 ... 13
1020 ... ''', "t2example")
1021 (0, 2)
1022 >>> common = ">>> assert 1 + 2 == 3\\n"
1023 >>> t1.runstring(common, "common")
1024 (0, 1)
1025 >>> t2.runstring(common, "common")
1026 (0, 1)
1027 >>> t1.merge(t2)
1028 *** Tester.merge: 'common' in both testers; summing outcomes.
1029 >>> t1.summarize(1)
1030 3 items passed all tests:
1031 2 tests in common
1032 2 tests in t1example
1033 2 tests in t2example
1034 6 tests in 3 items.
1035 6 passed and 0 failed.
1036 Test passed.
1037 (0, 6)
1038 >>>
1039 """
1040
1041 d = self.name2ft
1042 for name, (f, t) in other.name2ft.items():
Raymond Hettinger54f02222002-06-01 14:18:47 +00001043 if name in d:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001044 print "*** Tester.merge: '" + name + "' in both" \
1045 " testers; summing outcomes."
1046 f2, t2 = d[name]
1047 f = f + f2
1048 t = t + t2
1049 d[name] = f, t
1050
1051 def __record_outcome(self, name, f, t):
Raymond Hettinger54f02222002-06-01 14:18:47 +00001052 if name in self.name2ft:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001053 print "*** Warning: '" + name + "' was tested before;", \
1054 "summing outcomes."
1055 f2, t2 = self.name2ft[name]
1056 f = f + f2
1057 t = t + t2
1058 self.name2ft[name] = f, t
1059
1060 def __runone(self, target, name):
1061 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +00001062 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001063 prefix, base = name[:i], name[i+1:]
1064 else:
1065 prefix, base = "", base
1066 if self.isprivate(prefix, base):
1067 return 0, 0
1068 return self.rundoc(target, name)
1069
1070master = None
1071
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001072def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +00001073 report=True, optionflags=0):
1074 """m=None, name=None, globs=None, verbose=None, isprivate=None,
1075 report=True, optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +00001076
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001077 Test examples in docstrings in functions and classes reachable
1078 from module m (or the current module if m is not supplied), starting
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001079 with m.__doc__. Unless isprivate is specified, private names
1080 are not skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001081
1082 Also test examples reachable from dict m.__test__ if it exists and is
1083 not None. m.__dict__ maps names to functions, classes and strings;
1084 function and class docstrings are tested even if the name is private;
1085 strings are tested directly, as if they were docstrings.
1086
1087 Return (#failures, #tests).
1088
1089 See doctest.__doc__ for an overview.
1090
1091 Optional keyword arg "name" gives the name of the module; by default
1092 use m.__name__.
1093
1094 Optional keyword arg "globs" gives a dict to be used as the globals
1095 when executing examples; by default, use m.__dict__. A copy of this
1096 dict is actually used for each docstring, so that each docstring's
1097 examples start with a clean slate.
1098
1099 Optional keyword arg "verbose" prints lots of stuff if true, prints
1100 only failures if false; by default, it's true iff "-v" is in sys.argv.
1101
1102 Optional keyword arg "isprivate" specifies a function used to
1103 determine whether a name is private. The default function is
Raymond Hettinger71adf7e2003-07-16 19:25:22 +00001104 treat all functions as public. Optionally, "isprivate" can be
1105 set to doctest.is_private to skip over functions marked as private
1106 using the underscore naming convention; see its docs for details.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001107
1108 Optional keyword arg "report" prints a summary at the end when true,
1109 else prints nothing at the end. In verbose mode, the summary is
1110 detailed, else very brief (in fact, empty if all tests passed).
1111
Tim Peters6ebe61f2003-06-27 20:48:05 +00001112 Optional keyword arg "optionflags" or's together module constants,
1113 and defaults to 0. This is new in 2.3. Possible values:
1114
1115 DONT_ACCEPT_TRUE_FOR_1
1116 By default, if an expected output block contains just "1",
1117 an actual output block containing just "True" is considered
1118 to be a match, and similarly for "0" versus "False". When
1119 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1120 is allowed.
1121
Tim Peters8a7d2d52001-01-16 07:10:57 +00001122 Advanced tomfoolery: testmod runs methods of a local instance of
1123 class doctest.Tester, then merges the results into (or creates)
1124 global Tester instance doctest.master. Methods of doctest.master
1125 can be called directly too, if you want to do something unusual.
1126 Passing report=0 to testmod is especially useful then, to delay
1127 displaying a summary. Invoke doctest.master.summarize(verbose)
1128 when you're done fiddling.
1129 """
1130
1131 global master
1132
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001133 if m is None:
1134 import sys
1135 # DWA - m will still be None if this wasn't invoked from the command
1136 # line, in which case the following TypeError is about as good an error
1137 # as we should expect
1138 m = sys.modules.get('__main__')
1139
Tim Peters7402f792001-10-02 03:53:41 +00001140 if not _ismodule(m):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001141 raise TypeError("testmod: module required; " + `m`)
1142 if name is None:
1143 name = m.__name__
Tim Peters6ebe61f2003-06-27 20:48:05 +00001144 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
1145 optionflags=optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001146 failures, tries = tester.rundoc(m, name)
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001147 f, t = tester.rundict(m.__dict__, name, m)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001148 failures += f
1149 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001150 if hasattr(m, "__test__"):
1151 testdict = m.__test__
1152 if testdict:
1153 if not hasattr(testdict, "items"):
1154 raise TypeError("testmod: module.__test__ must support "
1155 ".items(); " + `testdict`)
1156 f, t = tester.run__test__(testdict, name + ".__test__")
Tim Peters6ebe61f2003-06-27 20:48:05 +00001157 failures += f
1158 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001159 if report:
1160 tester.summarize()
1161 if master is None:
1162 master = tester
1163 else:
1164 master.merge(tester)
1165 return failures, tries
1166
Tim Petersdb3756d2003-06-29 05:30:48 +00001167###########################################################################
1168# Various doctest extensions, to make using doctest with unittest
1169# easier, and to help debugging when a doctest goes wrong. Original
1170# code by Jim Fulton.
1171
1172# Utilities.
1173
1174# If module is None, return the calling module (the module that called
1175# the routine that called _normalize_module -- this normally won't be
1176# doctest!). If module is a string, it should be the (possibly dotted)
1177# name of a module, and the (rightmost) module object is returned. Else
1178# module is returned untouched; the intent appears to be that module is
1179# already a module object in this case (although this isn't checked).
1180
1181def _normalize_module(module):
1182 import sys
1183
1184 if module is None:
1185 # Get our caller's caller's module.
1186 module = sys._getframe(2).f_globals['__name__']
1187 module = sys.modules[module]
1188
1189 elif isinstance(module, (str, unicode)):
1190 # The ["*"] at the end is a mostly meaningless incantation with
1191 # a crucial property: if, e.g., module is 'a.b.c', it convinces
1192 # __import__ to return c instead of a.
1193 module = __import__(module, globals(), locals(), ["*"])
1194
1195 return module
1196
1197# tests is a list of (testname, docstring, filename, lineno) tuples.
1198# If object has a __doc__ attr, and the __doc__ attr looks like it
1199# contains a doctest (specifically, if it contains an instance of '>>>'),
1200# then tuple
1201# prefix + name, object.__doc__, filename, lineno
1202# is appended to tests. Else tests is left alone.
1203# There is no return value.
1204
1205def _get_doctest(name, object, tests, prefix, filename='', lineno=''):
1206 doc = getattr(object, '__doc__', '')
1207 if isinstance(doc, basestring) and '>>>' in doc:
1208 tests.append((prefix + name, doc, filename, lineno))
1209
1210# tests is a list of (testname, docstring, filename, lineno) tuples.
1211# docstrings containing doctests are appended to tests (if any are found).
1212# items is a dict, like a module or class dict, mapping strings to objects.
1213# mdict is the global dict of a "home" module -- only objects belonging
1214# to this module are searched for docstrings. module is the module to
1215# which mdict belongs.
1216# prefix is a string to be prepended to an object's name when adding a
1217# tuple to tests.
1218# The objects (values) in items are examined (recursively), and doctests
1219# belonging to functions and classes in the home module are appended to
1220# tests.
1221# minlineno is a gimmick to try to guess the file-relative line number
1222# at which a doctest probably begins.
1223
1224def _extract_doctests(items, module, mdict, tests, prefix, minlineno=0):
1225
1226 for name, object in items:
1227 # Only interested in named objects.
1228 if not hasattr(object, '__name__'):
1229 continue
1230
1231 elif hasattr(object, 'func_globals'):
1232 # Looks like a function.
1233 if object.func_globals is not mdict:
1234 # Non-local function.
1235 continue
1236 code = getattr(object, 'func_code', None)
1237 filename = getattr(code, 'co_filename', '')
1238 lineno = getattr(code, 'co_firstlineno', -1) + 1
1239 if minlineno:
1240 minlineno = min(lineno, minlineno)
1241 else:
1242 minlineno = lineno
1243 _get_doctest(name, object, tests, prefix, filename, lineno)
1244
1245 elif hasattr(object, "__module__"):
1246 # Maybe a class-like thing, in which case we care.
1247 if object.__module__ != module.__name__:
1248 # Not the same module.
1249 continue
1250 if not (hasattr(object, '__dict__')
1251 and hasattr(object, '__bases__')):
1252 # Not a class.
1253 continue
1254
1255 lineno = _extract_doctests(object.__dict__.items(),
1256 module,
1257 mdict,
1258 tests,
1259 prefix + name + ".")
1260 # XXX "-3" is unclear.
1261 _get_doctest(name, object, tests, prefix,
1262 lineno="%s (or above)" % (lineno - 3))
1263
1264 return minlineno
1265
1266# Find all the doctests belonging to the module object.
1267# Return a list of
1268# (testname, docstring, filename, lineno)
1269# tuples.
1270
1271def _find_tests(module, prefix=None):
1272 if prefix is None:
1273 prefix = module.__name__
1274 mdict = module.__dict__
1275 tests = []
1276 # Get the module-level doctest (if any).
1277 _get_doctest(prefix, module, tests, '', lineno="1 (or above)")
1278 # Recursively search the module __dict__ for doctests.
1279 if prefix:
1280 prefix += "."
1281 _extract_doctests(mdict.items(), module, mdict, tests, prefix)
1282 return tests
1283
1284# unittest helpers.
1285
1286# A function passed to unittest, for unittest to drive.
1287# tester is doctest Tester instance. doc is the docstring whose
1288# doctests are to be run.
1289
1290def _utest(tester, name, doc, filename, lineno):
1291 import sys
1292 from StringIO import StringIO
1293
1294 old = sys.stdout
1295 sys.stdout = new = StringIO()
1296 try:
1297 failures, tries = tester.runstring(doc, name)
1298 finally:
1299 sys.stdout = old
1300
1301 if failures:
1302 msg = new.getvalue()
1303 lname = '.'.join(name.split('.')[-1:])
1304 if not lineno:
1305 lineno = "0 (don't know line number)"
1306 # Don't change this format! It was designed so that Emacs can
1307 # parse it naturally.
1308 raise DocTestTestFailure('Failed doctest test for %s\n'
1309 ' File "%s", line %s, in %s\n\n%s' %
1310 (name, filename, lineno, lname, msg))
1311
1312class DocTestTestFailure(Exception):
1313 """A doctest test failed"""
1314
1315def DocTestSuite(module=None):
1316 """Convert doctest tests for a module to a unittest TestSuite.
1317
1318 The returned TestSuite is to be run by the unittest framework, and
1319 runs each doctest in the module. If any of the doctests fail,
1320 then the synthesized unit test fails, and an error is raised showing
1321 the name of the file containing the test and a (sometimes approximate)
1322 line number.
1323
1324 The optional module argument provides the module to be tested. It
1325 can be a module object or a (possibly dotted) module name. If not
1326 specified, the module calling DocTestSuite() is used.
1327
1328 Example (although note that unittest supplies many ways to use the
1329 TestSuite returned; see the unittest docs):
1330
1331 import unittest
1332 import doctest
1333 import my_module_with_doctests
1334
1335 suite = doctest.DocTestSuite(my_module_with_doctests)
1336 runner = unittest.TextTestRunner()
1337 runner.run(suite)
1338 """
1339
1340 import unittest
1341
1342 module = _normalize_module(module)
1343 tests = _find_tests(module)
1344 if not tests:
1345 raise ValueError(module, "has no tests")
1346
1347 tests.sort()
1348 suite = unittest.TestSuite()
1349 tester = Tester(module)
1350 for name, doc, filename, lineno in tests:
1351 if not filename:
1352 filename = module.__file__
1353 if filename.endswith(".pyc"):
1354 filename = filename[:-1]
1355 elif filename.endswith(".pyo"):
1356 filename = filename[:-1]
1357 def runit(name=name, doc=doc, filename=filename, lineno=lineno):
1358 _utest(tester, name, doc, filename, lineno)
1359 suite.addTest(unittest.FunctionTestCase(
1360 runit,
1361 description="doctest of " + name))
1362 return suite
1363
1364# Debugging support.
1365
1366def _expect(expect):
1367 # Return the expected output (if any), formatted as a Python
1368 # comment block.
1369 if expect:
1370 expect = "\n# ".join(expect.split("\n"))
1371 expect = "\n# Expect:\n# %s" % expect
1372 return expect
1373
1374def testsource(module, name):
1375 """Extract the doctest examples from a docstring.
1376
1377 Provide the module (or dotted name of the module) containing the
1378 tests to be extracted, and the name (within the module) of the object
1379 with the docstring containing the tests to be extracted.
1380
1381 The doctest examples are returned as a string containing Python
1382 code. The expected output blocks in the examples are converted
1383 to Python comments.
1384 """
1385
1386 module = _normalize_module(module)
1387 tests = _find_tests(module, "")
1388 test = [doc for (tname, doc, dummy, dummy) in tests
1389 if tname == name]
1390 if not test:
1391 raise ValueError(name, "not found in tests")
1392 test = test[0]
1393 examples = [source + _expect(expect)
1394 for source, expect, dummy in _extract_examples(test)]
1395 return '\n'.join(examples)
1396
1397def debug(module, name):
1398 """Debug a single docstring containing doctests.
1399
1400 Provide the module (or dotted name of the module) containing the
1401 docstring to be debugged, and the name (within the module) of the
1402 object with the docstring to be debugged.
1403
1404 The doctest examples are extracted (see function testsource()),
1405 and written to a temp file. The Python debugger (pdb) is then
1406 invoked on that file.
1407 """
1408
1409 import os
1410 import pdb
1411 import tempfile
1412
1413 module = _normalize_module(module)
1414 testsrc = testsource(module, name)
1415 srcfilename = tempfile.mktemp("doctestdebug.py")
1416 f = file(srcfilename, 'w')
1417 f.write(testsrc)
1418 f.close()
1419
1420 globs = {}
1421 globs.update(module.__dict__)
1422 try:
1423 # Note that %r is vital here. '%s' instead can, e.g., cause
1424 # backslashes to get treated as metacharacters on Windows.
1425 pdb.run("execfile(%r)" % srcfilename, globs, globs)
1426 finally:
1427 os.remove(srcfilename)
1428
1429
1430
Tim Peters8a7d2d52001-01-16 07:10:57 +00001431class _TestClass:
1432 """
1433 A pointless class, for sanity-checking of docstring testing.
1434
1435 Methods:
1436 square()
1437 get()
1438
1439 >>> _TestClass(13).get() + _TestClass(-12).get()
1440 1
1441 >>> hex(_TestClass(13).square().get())
1442 '0xa9'
1443 """
1444
1445 def __init__(self, val):
1446 """val -> _TestClass object with associated value val.
1447
1448 >>> t = _TestClass(123)
1449 >>> print t.get()
1450 123
1451 """
1452
1453 self.val = val
1454
1455 def square(self):
1456 """square() -> square TestClass's associated value
1457
1458 >>> _TestClass(13).square().get()
1459 169
1460 """
1461
1462 self.val = self.val ** 2
1463 return self
1464
1465 def get(self):
1466 """get() -> return TestClass's associated value.
1467
1468 >>> x = _TestClass(-42)
1469 >>> print x.get()
1470 -42
1471 """
1472
1473 return self.val
1474
1475__test__ = {"_TestClass": _TestClass,
1476 "string": r"""
1477 Example of a string object, searched as-is.
1478 >>> x = 1; y = 2
1479 >>> x + y, x * y
1480 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001481 """,
1482 "bool-int equivalence": r"""
1483 In 2.2, boolean expressions displayed
1484 0 or 1. By default, we still accept
1485 them. This can be disabled by passing
1486 DONT_ACCEPT_TRUE_FOR_1 to the new
1487 optionflags argument.
1488 >>> 4 == 4
1489 1
1490 >>> 4 == 4
1491 True
1492 >>> 4 > 4
1493 0
1494 >>> 4 > 4
1495 False
1496 """,
Tim Peters8a7d2d52001-01-16 07:10:57 +00001497 }
1498
1499def _test():
1500 import doctest
1501 return doctest.testmod(doctest)
1502
1503if __name__ == "__main__":
1504 _test()