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