blob: 8bda8d6c5fb7274c7fa7c245aad24211eab53684 [file] [log] [blame]
Tim Peters4fd9e2f2001-08-18 00:05:50 +00001# Module doctest.
Tim Peters8a7d2d52001-01-16 07:10:57 +00002# Released to the public domain 16-Jan-2001,
3# by Tim Peters (tim.one@home.com).
4
5# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
6
7"""Module doctest -- a framework for running examples in docstrings.
8
9NORMAL USAGE
10
11In normal use, end each module M with:
12
13def _test():
14 import doctest, M # replace M with your module's name
15 return doctest.testmod(M) # ditto
16
17if __name__ == "__main__":
18 _test()
19
20Then running the module as a script will cause the examples in the
21docstrings to get executed and verified:
22
23python M.py
24
25This won't display anything unless an example fails, in which case the
26failing example(s) and the cause(s) of the failure(s) are printed to stdout
27(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
28line of output is "Test failed.".
29
30Run it with the -v switch instead:
31
32python M.py -v
33
34and a detailed report of all examples tried is printed to stdout, along
35with assorted summaries at the end.
36
37You can force verbose mode by passing "verbose=1" to testmod, or prohibit
38it by passing "verbose=0". In either of those cases, sys.argv is not
39examined by testmod.
40
41In any case, testmod returns a 2-tuple of ints (f, t), where f is the
42number of docstring examples that failed and t is the total number of
43docstring examples attempted.
44
45
46WHICH DOCSTRINGS ARE EXAMINED?
47
48+ M.__doc__.
49
50+ f.__doc__ for all functions f in M.__dict__.values(), except those
Tim Peters7402f792001-10-02 03:53:41 +000051 with private names and those defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000052
53+ C.__doc__ for all classes C in M.__dict__.values(), except those with
Tim Peters7402f792001-10-02 03:53:41 +000054 private names and those defined in other modules.
Tim Peters8a7d2d52001-01-16 07:10:57 +000055
56+ If M.__test__ exists and "is true", it must be a dict, and
57 each entry maps a (string) name to a function object, class object, or
58 string. Function and class object docstrings found from M.__test__
59 are searched even if the name is private, and strings are searched
60 directly as if they were docstrings. In output, a key K in M.__test__
61 appears with name
62 <name of M>.__test__.K
63
64Any classes found are recursively searched similarly, to test docstrings in
65their contained methods and nested classes. Private names reached from M's
66globals are skipped, but all names reached from M.__test__ are searched.
67
68By default, a name is considered to be private if it begins with an
69underscore (like "_my_func") but doesn't both begin and end with (at least)
70two underscores (like "__init__"). You can change the default by passing
71your own "isprivate" function to testmod.
72
73If you want to test docstrings in objects with private names too, stuff
74them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
75own isprivate function to Tester's constructor, or call the rundoc method
76of a Tester instance).
77
Tim Peters8a7d2d52001-01-16 07:10:57 +000078WHAT'S THE EXECUTION CONTEXT?
79
80By default, each time testmod finds a docstring to test, it uses a *copy*
81of M's globals (so that running tests on a module doesn't change the
82module's real globals, and so that one test in M can't leave behind crumbs
83that accidentally allow another test to work). This means examples can
84freely use any names defined at top-level in M. It also means that sloppy
85imports (see above) can cause examples in external docstrings to use
86globals inappropriate for them.
87
88You can force use of your own dict as the execution context by passing
89"globs=your_dict" to testmod instead. Presumably this would be a copy of
90M.__dict__ merged with the globals from other imported modules.
91
92
93WHAT IF I WANT TO TEST A WHOLE PACKAGE?
94
95Piece o' cake, provided the modules do their testing from docstrings.
96Here's the test.py I use for the world's most elaborate Rational/
97floating-base-conversion pkg (which I'll distribute some day):
98
99from Rational import Cvt
100from Rational import Format
101from Rational import machprec
102from Rational import Rat
103from Rational import Round
104from Rational import utils
105
106modules = (Cvt,
107 Format,
108 machprec,
109 Rat,
110 Round,
111 utils)
112
113def _test():
114 import doctest
115 import sys
116 verbose = "-v" in sys.argv
117 for mod in modules:
118 doctest.testmod(mod, verbose=verbose, report=0)
119 doctest.master.summarize()
120
121if __name__ == "__main__":
122 _test()
123
124IOW, it just runs testmod on all the pkg modules. testmod remembers the
125names and outcomes (# of failures, # of tries) for each item it's seen, and
126passing "report=0" prevents it from printing a summary in verbose mode.
127Instead, the summary is delayed until all modules have been tested, and
128then "doctest.master.summarize()" forces the summary at the end.
129
130So this is very nice in practice: each module can be tested individually
131with almost no work beyond writing up docstring examples, and collections
132of modules can be tested too as a unit with no more work than the above.
133
134
135WHAT ABOUT EXCEPTIONS?
136
137No problem, as long as the only output generated by the example is the
138traceback itself. For example:
139
Tim Peters60e23f42001-02-14 00:43:21 +0000140 >>> [1, 2, 3].remove(42)
Tim Petersea4f9312001-02-13 20:54:42 +0000141 Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000142 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000143 ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000144 >>>
145
146Note that only the exception type and value are compared (specifically,
147only the last line in the traceback).
148
149
150ADVANCED USAGE
151
152doctest.testmod() captures the testing policy I find most useful most
153often. You may want other policies.
154
155testmod() actually creates a local instance of class doctest.Tester, runs
156appropriate methods of that class, and merges the results into global
157Tester instance doctest.master.
158
159You can create your own instances of doctest.Tester, and so build your own
160policies, or even run methods of doctest.master directly. See
161doctest.Tester.__doc__ for details.
162
163
164SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
165
166Oh ya. It's easy! In most cases a copy-and-paste of an interactive
167console session works fine -- just make sure the leading whitespace is
168rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
169right, but doctest is not in the business of guessing what you think a tab
170means).
171
172 >>> # comments are ignored
173 >>> x = 12
174 >>> x
175 12
176 >>> if x == 13:
177 ... print "yes"
178 ... else:
179 ... print "no"
180 ... print "NO"
181 ... print "NO!!!"
182 ...
183 no
184 NO
185 NO!!!
186 >>>
187
188Any expected output must immediately follow the final ">>>" or "..." line
189containing the code, and the expected output (if any) extends to the next
190">>>" or all-whitespace line. That's it.
191
192Bummers:
193
194+ Expected output cannot contain an all-whitespace line, since such a line
195 is taken to signal the end of expected output.
196
197+ Output to stdout is captured, but not output to stderr (exception
198 tracebacks are captured via a different means).
199
200+ If you continue a line via backslashing in an interactive session, or for
201 any other reason use a backslash, you need to double the backslash in the
202 docstring version. This is simply because you're in a string, and so the
203 backslash must be escaped for it to survive intact. Like:
204
205>>> if "yes" == \\
206... "y" + \\
207... "es": # in the source code you'll see the doubled backslashes
208... print 'yes'
209yes
210
211The starting column doesn't matter:
212
213>>> assert "Easy!"
214 >>> import math
215 >>> math.floor(1.9)
216 1.0
217
218and as many leading whitespace characters are stripped from the expected
219output as appeared in the initial ">>>" line that triggered it.
220
221If you execute this very file, the examples above will be found and
222executed, leading to this output in verbose mode:
223
224Running doctest.__doc__
Tim Peters60e23f42001-02-14 00:43:21 +0000225Trying: [1, 2, 3].remove(42)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000226Expecting:
Tim Petersea4f9312001-02-13 20:54:42 +0000227Traceback (most recent call last):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000228 File "<stdin>", line 1, in ?
Tim Peters60e23f42001-02-14 00:43:21 +0000229ValueError: list.remove(x): x not in list
Tim Peters8a7d2d52001-01-16 07:10:57 +0000230ok
231Trying: x = 12
232Expecting: nothing
233ok
234Trying: x
235Expecting: 12
236ok
237Trying:
238if x == 13:
239 print "yes"
240else:
241 print "no"
242 print "NO"
243 print "NO!!!"
244Expecting:
245no
246NO
247NO!!!
248ok
249... and a bunch more like that, with this summary at the end:
250
2515 items had no tests:
252 doctest.Tester.__init__
253 doctest.Tester.run__test__
254 doctest.Tester.summarize
255 doctest.run_docstring_examples
256 doctest.testmod
25712 items passed all tests:
258 8 tests in doctest
259 6 tests in doctest.Tester
260 10 tests in doctest.Tester.merge
Tim Peters17111f32001-10-03 04:08:26 +0000261 14 tests in doctest.Tester.rundict
Tim Peters8a7d2d52001-01-16 07:10:57 +0000262 3 tests in doctest.Tester.rundoc
263 3 tests in doctest.Tester.runstring
264 2 tests in doctest.__test__._TestClass
265 2 tests in doctest.__test__._TestClass.__init__
266 2 tests in doctest.__test__._TestClass.get
267 1 tests in doctest.__test__._TestClass.square
268 2 tests in doctest.__test__.string
269 7 tests in doctest.is_private
Tim Peters17111f32001-10-03 04:08:26 +000027060 tests in 17 items.
27160 passed and 0 failed.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000272Test passed.
273"""
274
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000275__all__ = [
276 'testmod',
277 'run_docstring_examples',
278 'is_private',
279 'Tester',
280]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000281
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000282import __future__
Tim Peters8a7d2d52001-01-16 07:10:57 +0000283
Tim Peters8a7d2d52001-01-16 07:10:57 +0000284import re
285PS1 = ">>>"
286PS2 = "..."
287_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
288_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
289_isEmpty = re.compile(r"\s*$").match
290_isComment = re.compile(r"\s*#").match
291del re
292
Tim Peters7402f792001-10-02 03:53:41 +0000293from types import StringTypes as _StringTypes
294
295from inspect import isclass as _isclass
296from inspect import isfunction as _isfunction
297from inspect import ismodule as _ismodule
Tim Peters17111f32001-10-03 04:08:26 +0000298from inspect import classify_class_attrs as _classify_class_attrs
Tim Peters7402f792001-10-02 03:53:41 +0000299
Tim Peters6ebe61f2003-06-27 20:48:05 +0000300# Option constants.
301DONT_ACCEPT_TRUE_FOR_1 = 1 << 0
302
Tim Peters8a7d2d52001-01-16 07:10:57 +0000303# Extract interactive examples from a string. Return a list of triples,
304# (source, outcome, lineno). "source" is the source code, and ends
305# with a newline iff the source spans more than one line. "outcome" is
306# the expected output if any, else an empty string. When not empty,
307# outcome always ends with a newline. "lineno" is the line number,
308# 0-based wrt the start of the string, of the first source line.
309
310def _extract_examples(s):
311 isPS1, isPS2 = _isPS1, _isPS2
312 isEmpty, isComment = _isEmpty, _isComment
313 examples = []
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000314 lines = s.split("\n")
Tim Peters8a7d2d52001-01-16 07:10:57 +0000315 i, n = 0, len(lines)
316 while i < n:
317 line = lines[i]
318 i = i + 1
319 m = isPS1(line)
320 if m is None:
321 continue
322 j = m.end(0) # beyond the prompt
323 if isEmpty(line, j) or isComment(line, j):
324 # a bare prompt or comment -- not interesting
325 continue
326 lineno = i - 1
327 if line[j] != " ":
328 raise ValueError("line " + `lineno` + " of docstring lacks "
329 "blank after " + PS1 + ": " + line)
330 j = j + 1
331 blanks = m.group(1)
332 nblanks = len(blanks)
333 # suck up this and following PS2 lines
334 source = []
335 while 1:
336 source.append(line[j:])
337 line = lines[i]
338 m = isPS2(line)
339 if m:
340 if m.group(1) != blanks:
341 raise ValueError("inconsistent leading whitespace "
342 "in line " + `i` + " of docstring: " + line)
343 i = i + 1
344 else:
345 break
346 if len(source) == 1:
347 source = source[0]
348 else:
349 # get rid of useless null line from trailing empty "..."
350 if source[-1] == "":
351 del source[-1]
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000352 source = "\n".join(source) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000353 # suck up response
354 if isPS1(line) or isEmpty(line):
355 expect = ""
356 else:
357 expect = []
358 while 1:
359 if line[:nblanks] != blanks:
360 raise ValueError("inconsistent leading whitespace "
361 "in line " + `i` + " of docstring: " + line)
362 expect.append(line[nblanks:])
363 i = i + 1
364 line = lines[i]
365 if isPS1(line) or isEmpty(line):
366 break
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000367 expect = "\n".join(expect) + "\n"
Tim Peters8a7d2d52001-01-16 07:10:57 +0000368 examples.append( (source, expect, lineno) )
369 return examples
370
371# Capture stdout when running examples.
372
373class _SpoofOut:
374 def __init__(self):
375 self.clear()
376 def write(self, s):
377 self.buf.append(s)
378 def get(self):
Tim Petersf9bb4962001-02-14 06:35:35 +0000379 guts = "".join(self.buf)
380 # If anything at all was written, make sure there's a trailing
381 # newline. There's no way for the expected output to indicate
382 # that a trailing newline is missing.
383 if guts and not guts.endswith("\n"):
384 guts = guts + "\n"
Tim Petersc77db342001-10-23 02:21:52 +0000385 # Prevent softspace from screwing up the next test case, in
386 # case they used print with a trailing comma in an example.
387 if hasattr(self, "softspace"):
388 del self.softspace
Tim Petersf9bb4962001-02-14 06:35:35 +0000389 return guts
Tim Peters8a7d2d52001-01-16 07:10:57 +0000390 def clear(self):
391 self.buf = []
Tim Petersc77db342001-10-23 02:21:52 +0000392 if hasattr(self, "softspace"):
393 del self.softspace
Tim Peters8a7d2d52001-01-16 07:10:57 +0000394 def flush(self):
395 # JPython calls flush
396 pass
397
398# Display some tag-and-msg pairs nicely, keeping the tag and its msg
399# on the same line when that makes sense.
400
401def _tag_out(printer, *tag_msg_pairs):
402 for tag, msg in tag_msg_pairs:
403 printer(tag + ":")
404 msg_has_nl = msg[-1:] == "\n"
405 msg_has_two_nl = msg_has_nl and \
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000406 msg.find("\n") < len(msg) - 1
Tim Peters8a7d2d52001-01-16 07:10:57 +0000407 if len(tag) + len(msg) < 76 and not msg_has_two_nl:
408 printer(" ")
409 else:
410 printer("\n")
411 printer(msg)
412 if not msg_has_nl:
413 printer("\n")
414
415# Run list of examples, in context globs. "out" can be used to display
416# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
417# that captures the examples' std output. Return (#failures, #tries).
418
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000419def _run_examples_inner(out, fakeout, examples, globs, verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000420 compileflags, optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000421 import sys, traceback
422 OK, BOOM, FAIL = range(3)
423 NADA = "nothing"
424 stderr = _SpoofOut()
425 failures = 0
426 for source, want, lineno in examples:
427 if verbose:
428 _tag_out(out, ("Trying", source),
429 ("Expecting", want or NADA))
430 fakeout.clear()
431 try:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000432 exec compile(source, "<string>", "single",
433 compileflags, 1) in globs
Tim Peters8a7d2d52001-01-16 07:10:57 +0000434 got = fakeout.get()
435 state = OK
Tim Petersbcc2c122002-03-20 19:32:03 +0000436 except KeyboardInterrupt:
437 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000438 except:
439 # See whether the exception was expected.
Tim Petersea4f9312001-02-13 20:54:42 +0000440 if want.find("Traceback (innermost last):\n") == 0 or \
441 want.find("Traceback (most recent call last):\n") == 0:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000442 # Only compare exception type and value - the rest of
443 # the traceback isn't necessary.
Eric S. Raymond630e69c2001-02-09 08:33:43 +0000444 want = want.split('\n')[-2] + '\n'
Tim Peters77f2d502001-06-24 18:59:01 +0000445 exc_type, exc_val = sys.exc_info()[:2]
Tim Peters08bba952001-06-24 06:46:58 +0000446 got = traceback.format_exception_only(exc_type, exc_val)[-1]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000447 state = OK
448 else:
449 # unexpected exception
450 stderr.clear()
451 traceback.print_exc(file=stderr)
452 state = BOOM
453
454 if state == OK:
Tim Peters6ebe61f2003-06-27 20:48:05 +0000455 if (got == want or
456 (not (optionflags & DONT_ACCEPT_TRUE_FOR_1) and
457 (got, want) in (("True\n", "1\n"), ("False\n", "0\n"))
458 )
459 ):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000460 if verbose:
461 out("ok\n")
462 continue
463 state = FAIL
464
465 assert state in (FAIL, BOOM)
466 failures = failures + 1
467 out("*" * 65 + "\n")
468 _tag_out(out, ("Failure in example", source))
469 out("from line #" + `lineno` + " of " + name + "\n")
470 if state == FAIL:
471 _tag_out(out, ("Expected", want or NADA), ("Got", got))
472 else:
473 assert state == BOOM
474 _tag_out(out, ("Exception raised", stderr.get()))
475
476 return failures, len(examples)
477
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000478# Get the future-flags associated with the future features that have been
479# imported into globs.
480
481def _extract_future_flags(globs):
482 flags = 0
483 for fname in __future__.all_feature_names:
484 feature = globs.get(fname, None)
485 if feature is getattr(__future__, fname):
486 flags |= feature.compiler_flag
487 return flags
488
Tim Petersd4ad59e2001-06-24 20:02:47 +0000489# Run list of examples, in a shallow copy of context (dict) globs.
490# Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000491
Tim Peters6ebe61f2003-06-27 20:48:05 +0000492def _run_examples(examples, globs, verbose, name, compileflags,
493 optionflags):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000494 import sys
495 saveout = sys.stdout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000496 globs = globs.copy()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000497 try:
498 sys.stdout = fakeout = _SpoofOut()
499 x = _run_examples_inner(saveout.write, fakeout, examples,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000500 globs, verbose, name, compileflags,
501 optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000502 finally:
503 sys.stdout = saveout
Tim Petersd4ad59e2001-06-24 20:02:47 +0000504 # While Python gc can clean up most cycles on its own, it doesn't
505 # chase frame objects. This is especially irksome when running
506 # generator tests that raise exceptions, because a named generator-
507 # iterator gets an entry in globs, and the generator-iterator
508 # object's frame's traceback info points back to globs. This is
Tim Petersfee69d02001-06-24 20:24:16 +0000509 # easy to break just by clearing the namespace. This can also
510 # help to break other kinds of cycles, and even for cycles that
511 # gc can break itself it's better to break them ASAP.
Tim Petersd4ad59e2001-06-24 20:02:47 +0000512 globs.clear()
Tim Peters8a7d2d52001-01-16 07:10:57 +0000513 return x
514
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000515def run_docstring_examples(f, globs, verbose=0, name="NoName",
Tim Peters6ebe61f2003-06-27 20:48:05 +0000516 compileflags=None, optionflags=0):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000517 """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
518
Tim Petersd4ad59e2001-06-24 20:02:47 +0000519 Use (a shallow copy of) dict globs as the globals for execution.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000520 Return (#failures, #tries).
521
522 If optional arg verbose is true, print stuff even if there are no
523 failures.
524 Use string name in failure msgs.
525 """
526
527 try:
528 doc = f.__doc__
529 if not doc:
530 # docstring empty or None
531 return 0, 0
532 # just in case CT invents a doc object that has to be forced
533 # to look like a string <0.9 wink>
534 doc = str(doc)
Tim Petersbcc2c122002-03-20 19:32:03 +0000535 except KeyboardInterrupt:
536 raise
Tim Peters8a7d2d52001-01-16 07:10:57 +0000537 except:
538 return 0, 0
539
540 e = _extract_examples(doc)
541 if not e:
542 return 0, 0
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000543 if compileflags is None:
544 compileflags = _extract_future_flags(globs)
Tim Peters6ebe61f2003-06-27 20:48:05 +0000545 return _run_examples(e, globs, verbose, name, compileflags, optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000546
547def is_private(prefix, base):
548 """prefix, base -> true iff name prefix + "." + base is "private".
549
550 Prefix may be an empty string, and base does not contain a period.
551 Prefix is ignored (although functions you write conforming to this
552 protocol may make use of it).
553 Return true iff base begins with an (at least one) underscore, but
554 does not both begin and end with (at least) two underscores.
555
556 >>> is_private("a.b", "my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000557 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000558 >>> is_private("____", "_my_func")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000559 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000560 >>> is_private("someclass", "__init__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000561 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000562 >>> is_private("sometypo", "__init_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000563 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000564 >>> is_private("x.y.z", "_")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000565 True
Tim Peters8a7d2d52001-01-16 07:10:57 +0000566 >>> is_private("_x.y.z", "__")
Guido van Rossum77f6a652002-04-03 22:41:51 +0000567 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000568 >>> is_private("", "") # senseless but consistent
Guido van Rossum77f6a652002-04-03 22:41:51 +0000569 False
Tim Peters8a7d2d52001-01-16 07:10:57 +0000570 """
571
572 return base[:1] == "_" and not base[:2] == "__" == base[-2:]
573
Tim Peters7402f792001-10-02 03:53:41 +0000574# Determine if a class of function was defined in the given module.
575
576def _from_module(module, object):
577 if _isfunction(object):
578 return module.__dict__ is object.func_globals
579 if _isclass(object):
580 return module.__name__ == object.__module__
581 raise ValueError("object must be a class or function")
582
Tim Peters8a7d2d52001-01-16 07:10:57 +0000583class Tester:
584 """Class Tester -- runs docstring examples and accumulates stats.
585
586In normal use, function doctest.testmod() hides all this from you,
587so use that if you can. Create your own instances of Tester to do
588fancier things.
589
590Methods:
591 runstring(s, name)
592 Search string s for examples to run; use name for logging.
593 Return (#failures, #tries).
594
595 rundoc(object, name=None)
596 Search object.__doc__ for examples to run; use name (or
597 object.__name__) for logging. Return (#failures, #tries).
598
Tim Peters7402f792001-10-02 03:53:41 +0000599 rundict(d, name, module=None)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000600 Search for examples in docstrings in all of d.values(); use name
Tim Peters7402f792001-10-02 03:53:41 +0000601 for logging. Exclude functions and classes not defined in module
602 if specified. Return (#failures, #tries).
Tim Peters8a7d2d52001-01-16 07:10:57 +0000603
604 run__test__(d, name)
605 Treat dict d like module.__test__. Return (#failures, #tries).
606
607 summarize(verbose=None)
608 Display summary of testing results, to stdout. Return
609 (#failures, #tries).
610
611 merge(other)
612 Merge in the test results from Tester instance "other".
613
614>>> from doctest import Tester
615>>> t = Tester(globs={'x': 42}, verbose=0)
616>>> t.runstring(r'''
617... >>> x = x * 2
618... >>> print x
619... 42
620... ''', 'XYZ')
621*****************************************************************
622Failure in example: print x
623from line #2 of XYZ
624Expected: 42
625Got: 84
626(1, 2)
627>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
628(0, 2)
629>>> t.summarize()
Guido van Rossum261d91a2001-03-18 17:05:58 +0000630*****************************************************************
Tim Peters8a7d2d52001-01-16 07:10:57 +00006311 items had failures:
632 1 of 2 in XYZ
633***Test Failed*** 1 failures.
634(1, 4)
635>>> t.summarize(verbose=1)
6361 items passed all tests:
637 2 tests in example2
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
6414 tests in 2 items.
6423 passed and 1 failed.
643***Test Failed*** 1 failures.
644(1, 4)
645>>>
646"""
647
648 def __init__(self, mod=None, globs=None, verbose=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000649 isprivate=None, optionflags=0):
650 """mod=None, globs=None, verbose=None, isprivate=None,
651optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +0000652
653See doctest.__doc__ for an overview.
654
655Optional keyword arg "mod" is a module, whose globals are used for
656executing examples. If not specified, globs must be specified.
657
658Optional keyword arg "globs" gives a dict to be used as the globals
659when executing examples; if not specified, use the globals from
660module mod.
661
662In either case, a copy of the dict is used for each docstring
663examined.
664
665Optional keyword arg "verbose" prints lots of stuff if true, only
666failures if false; by default, it's true iff "-v" is in sys.argv.
667
668Optional keyword arg "isprivate" specifies a function used to determine
669whether a name is private. The default function is doctest.is_private;
670see its docs for details.
Tim Peters6ebe61f2003-06-27 20:48:05 +0000671
672See doctest.testmod docs for the meaning of optionflags.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000673"""
674
675 if mod is None and globs is None:
676 raise TypeError("Tester.__init__: must specify mod or globs")
Tim Peters7402f792001-10-02 03:53:41 +0000677 if mod is not None and not _ismodule(mod):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000678 raise TypeError("Tester.__init__: mod must be a module; " +
679 `mod`)
680 if globs is None:
681 globs = mod.__dict__
682 self.globs = globs
683
684 if verbose is None:
685 import sys
686 verbose = "-v" in sys.argv
687 self.verbose = verbose
688
689 if isprivate is None:
690 isprivate = is_private
691 self.isprivate = isprivate
692
Tim Peters6ebe61f2003-06-27 20:48:05 +0000693 self.optionflags = optionflags
694
Tim Peters8a7d2d52001-01-16 07:10:57 +0000695 self.name2ft = {} # map name to (#failures, #trials) pair
696
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000697 self.compileflags = _extract_future_flags(globs)
698
Tim Peters8a7d2d52001-01-16 07:10:57 +0000699 def runstring(self, s, name):
700 """
701 s, name -> search string s for examples to run, logging as name.
702
703 Use string name as the key for logging the outcome.
704 Return (#failures, #examples).
705
706 >>> t = Tester(globs={}, verbose=1)
707 >>> test = r'''
708 ... # just an example
709 ... >>> x = 1 + 2
710 ... >>> x
711 ... 3
712 ... '''
713 >>> t.runstring(test, "Example")
714 Running string Example
715 Trying: x = 1 + 2
716 Expecting: nothing
717 ok
718 Trying: x
719 Expecting: 3
720 ok
721 0 of 2 examples failed in string Example
722 (0, 2)
723 """
724
725 if self.verbose:
726 print "Running string", name
727 f = t = 0
728 e = _extract_examples(s)
729 if e:
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000730 f, t = _run_examples(e, self.globs, self.verbose, name,
Tim Peters6ebe61f2003-06-27 20:48:05 +0000731 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000732 if self.verbose:
733 print f, "of", t, "examples failed in string", name
734 self.__record_outcome(name, f, t)
735 return f, t
736
737 def rundoc(self, object, name=None):
738 """
739 object, name=None -> search object.__doc__ for examples to run.
740
741 Use optional string name as the key for logging the outcome;
742 by default use object.__name__.
743 Return (#failures, #examples).
744 If object is a class object, search recursively for method
745 docstrings too.
746 object.__doc__ is examined regardless of name, but if object is
747 a class, whether private names reached from object are searched
748 depends on the constructor's "isprivate" argument.
749
750 >>> t = Tester(globs={}, verbose=0)
751 >>> def _f():
752 ... '''Trivial docstring example.
753 ... >>> assert 2 == 2
754 ... '''
755 ... return 32
756 ...
757 >>> t.rundoc(_f) # expect 0 failures in 1 example
758 (0, 1)
759 """
760
761 if name is None:
762 try:
763 name = object.__name__
764 except AttributeError:
765 raise ValueError("Tester.rundoc: name must be given "
766 "when object.__name__ doesn't exist; " + `object`)
767 if self.verbose:
768 print "Running", name + ".__doc__"
Tim Peters4fd9e2f2001-08-18 00:05:50 +0000769 f, t = run_docstring_examples(object, self.globs, self.verbose, name,
Tim Peters275abbd2003-06-29 03:11:20 +0000770 self.compileflags, self.optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +0000771 if self.verbose:
772 print f, "of", t, "examples failed in", name + ".__doc__"
773 self.__record_outcome(name, f, t)
Tim Peters7402f792001-10-02 03:53:41 +0000774 if _isclass(object):
Tim Peters17111f32001-10-03 04:08:26 +0000775 # In 2.2, class and static methods complicate life. Build
776 # a dict "that works", by hook or by crook.
777 d = {}
778 for tag, kind, homecls, value in _classify_class_attrs(object):
779
780 if homecls is not object:
781 # Only look at names defined immediately by the class.
782 continue
783
784 elif self.isprivate(name, tag):
785 continue
786
787 elif kind == "method":
788 # value is already a function
789 d[tag] = value
790
791 elif kind == "static method":
792 # value isn't a function, but getattr reveals one
793 d[tag] = getattr(object, tag)
794
795 elif kind == "class method":
796 # Hmm. A classmethod object doesn't seem to reveal
797 # enough. But getattr turns it into a bound method,
798 # and from there .im_func retrieves the underlying
799 # function.
800 d[tag] = getattr(object, tag).im_func
801
802 elif kind == "property":
803 # The methods implementing the property have their
804 # own docstrings -- but the property may have one too.
805 if value.__doc__ is not None:
806 d[tag] = str(value.__doc__)
807
808 elif kind == "data":
809 # Grab nested classes.
810 if _isclass(value):
811 d[tag] = value
812
813 else:
814 raise ValueError("teach doctest about %r" % kind)
815
816 f2, t2 = self.run__test__(d, name)
817 f += f2
818 t += t2
819
Tim Peters8a7d2d52001-01-16 07:10:57 +0000820 return f, t
821
Tim Peters7402f792001-10-02 03:53:41 +0000822 def rundict(self, d, name, module=None):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000823 """
Tim Peters7402f792001-10-02 03:53:41 +0000824 d, name, module=None -> search for docstring examples in d.values().
Tim Peters8a7d2d52001-01-16 07:10:57 +0000825
826 For k, v in d.items() such that v is a function or class,
827 do self.rundoc(v, name + "." + k). Whether this includes
828 objects with private names depends on the constructor's
Tim Peters7402f792001-10-02 03:53:41 +0000829 "isprivate" argument. If module is specified, functions and
830 classes that are not defined in module are excluded.
Tim Peters8a7d2d52001-01-16 07:10:57 +0000831 Return aggregate (#failures, #examples).
832
Tim Peters7402f792001-10-02 03:53:41 +0000833 Build and populate two modules with sample functions to test that
834 exclusion of external functions and classes works.
835
836 >>> import new
837 >>> m1 = new.module('_m1')
838 >>> m2 = new.module('_m2')
839 >>> test_data = \"""
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000840 ... def _f():
Tim Peters7402f792001-10-02 03:53:41 +0000841 ... '''>>> assert 1 == 1
842 ... '''
843 ... def g():
Tim Peters8a7d2d52001-01-16 07:10:57 +0000844 ... '''>>> assert 2 != 1
845 ... '''
Tim Peters7402f792001-10-02 03:53:41 +0000846 ... class H:
847 ... '''>>> assert 2 > 1
848 ... '''
849 ... def bar(self):
850 ... '''>>> assert 1 < 2
851 ... '''
852 ... \"""
853 >>> exec test_data in m1.__dict__
854 >>> exec test_data in m2.__dict__
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000855 >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
Tim Peters7402f792001-10-02 03:53:41 +0000856
857 Tests that objects outside m1 are excluded:
858
Tim Peters8a7d2d52001-01-16 07:10:57 +0000859 >>> t = Tester(globs={}, verbose=0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000860 >>> t.rundict(m1.__dict__, "rundict_test", m1) # _f, f2 and g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000861 (0, 3)
862
863 Again, but with a custom isprivate function allowing _f:
864
Tim Peters8a7d2d52001-01-16 07:10:57 +0000865 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000866 >>> t.rundict(m1.__dict__, "rundict_test_pvt", m1) # Only f2, g2 and h2 skipped
Tim Peters7402f792001-10-02 03:53:41 +0000867 (0, 4)
868
869 And once more, not excluding stuff outside m1:
870
871 >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000872 >>> t.rundict(m1.__dict__, "rundict_test_pvt") # None are skipped.
Tim Peters7402f792001-10-02 03:53:41 +0000873 (0, 8)
Tim Peters4a9ac4a2001-10-02 22:47:08 +0000874
875 The exclusion of objects from outside the designated module is
876 meant to be invoked automagically by testmod.
877
878 >>> testmod(m1)
879 (0, 3)
880
Tim Peters8a7d2d52001-01-16 07:10:57 +0000881 """
882
883 if not hasattr(d, "items"):
884 raise TypeError("Tester.rundict: d must support .items(); " +
885 `d`)
886 f = t = 0
Tim Peters24a41912001-03-21 23:07:59 +0000887 # Run the tests by alpha order of names, for consistency in
888 # verbose-mode output.
889 names = d.keys()
890 names.sort()
891 for thisname in names:
892 value = d[thisname]
Tim Peters7402f792001-10-02 03:53:41 +0000893 if _isfunction(value) or _isclass(value):
894 if module and not _from_module(module, value):
895 continue
Tim Peters8a7d2d52001-01-16 07:10:57 +0000896 f2, t2 = self.__runone(value, name + "." + thisname)
897 f = f + f2
898 t = t + t2
899 return f, t
900
901 def run__test__(self, d, name):
902 """d, name -> Treat dict d like module.__test__.
903
904 Return (#failures, #tries).
905 See testmod.__doc__ for details.
906 """
907
908 failures = tries = 0
909 prefix = name + "."
910 savepvt = self.isprivate
911 try:
912 self.isprivate = lambda *args: 0
Tim Peters24a41912001-03-21 23:07:59 +0000913 # Run the tests by alpha order of names, for consistency in
914 # verbose-mode output.
915 keys = d.keys()
916 keys.sort()
917 for k in keys:
918 v = d[k]
Tim Peters8a7d2d52001-01-16 07:10:57 +0000919 thisname = prefix + k
Tim Peters7402f792001-10-02 03:53:41 +0000920 if type(v) in _StringTypes:
Tim Peters8a7d2d52001-01-16 07:10:57 +0000921 f, t = self.runstring(v, thisname)
Tim Peters7402f792001-10-02 03:53:41 +0000922 elif _isfunction(v) or _isclass(v):
Tim Peters8a7d2d52001-01-16 07:10:57 +0000923 f, t = self.rundoc(v, thisname)
924 else:
925 raise TypeError("Tester.run__test__: values in "
926 "dict must be strings, functions "
927 "or classes; " + `v`)
928 failures = failures + f
929 tries = tries + t
930 finally:
931 self.isprivate = savepvt
932 return failures, tries
933
934 def summarize(self, verbose=None):
935 """
936 verbose=None -> summarize results, return (#failures, #tests).
937
938 Print summary of test results to stdout.
939 Optional arg 'verbose' controls how wordy this is. By
940 default, use the verbose setting established by the
941 constructor.
942 """
943
944 if verbose is None:
945 verbose = self.verbose
946 notests = []
947 passed = []
948 failed = []
949 totalt = totalf = 0
950 for x in self.name2ft.items():
951 name, (f, t) = x
952 assert f <= t
953 totalt = totalt + t
954 totalf = totalf + f
955 if t == 0:
956 notests.append(name)
957 elif f == 0:
958 passed.append( (name, t) )
959 else:
960 failed.append(x)
961 if verbose:
962 if notests:
963 print len(notests), "items had no tests:"
964 notests.sort()
965 for thing in notests:
966 print " ", thing
967 if passed:
968 print len(passed), "items passed all tests:"
969 passed.sort()
970 for thing, count in passed:
971 print " %3d tests in %s" % (count, thing)
972 if failed:
Guido van Rossumaf00a462001-03-18 16:58:44 +0000973 print "*" * 65
Tim Peters8a7d2d52001-01-16 07:10:57 +0000974 print len(failed), "items had failures:"
975 failed.sort()
976 for thing, (f, t) in failed:
977 print " %3d of %3d in %s" % (f, t, thing)
978 if verbose:
979 print totalt, "tests in", len(self.name2ft), "items."
980 print totalt - totalf, "passed and", totalf, "failed."
981 if totalf:
982 print "***Test Failed***", totalf, "failures."
983 elif verbose:
984 print "Test passed."
985 return totalf, totalt
986
987 def merge(self, other):
988 """
989 other -> merge in test results from the other Tester instance.
990
991 If self and other both have a test result for something
992 with the same name, the (#failures, #tests) results are
993 summed, and a warning is printed to stdout.
994
995 >>> from doctest import Tester
996 >>> t1 = Tester(globs={}, verbose=0)
997 >>> t1.runstring('''
998 ... >>> x = 12
999 ... >>> print x
1000 ... 12
1001 ... ''', "t1example")
1002 (0, 2)
1003 >>>
1004 >>> t2 = Tester(globs={}, verbose=0)
1005 >>> t2.runstring('''
1006 ... >>> x = 13
1007 ... >>> print x
1008 ... 13
1009 ... ''', "t2example")
1010 (0, 2)
1011 >>> common = ">>> assert 1 + 2 == 3\\n"
1012 >>> t1.runstring(common, "common")
1013 (0, 1)
1014 >>> t2.runstring(common, "common")
1015 (0, 1)
1016 >>> t1.merge(t2)
1017 *** Tester.merge: 'common' in both testers; summing outcomes.
1018 >>> t1.summarize(1)
1019 3 items passed all tests:
1020 2 tests in common
1021 2 tests in t1example
1022 2 tests in t2example
1023 6 tests in 3 items.
1024 6 passed and 0 failed.
1025 Test passed.
1026 (0, 6)
1027 >>>
1028 """
1029
1030 d = self.name2ft
1031 for name, (f, t) in other.name2ft.items():
Raymond Hettinger54f02222002-06-01 14:18:47 +00001032 if name in d:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001033 print "*** Tester.merge: '" + name + "' in both" \
1034 " testers; summing outcomes."
1035 f2, t2 = d[name]
1036 f = f + f2
1037 t = t + t2
1038 d[name] = f, t
1039
1040 def __record_outcome(self, name, f, t):
Raymond Hettinger54f02222002-06-01 14:18:47 +00001041 if name in self.name2ft:
Tim Peters8a7d2d52001-01-16 07:10:57 +00001042 print "*** Warning: '" + name + "' was tested before;", \
1043 "summing outcomes."
1044 f2, t2 = self.name2ft[name]
1045 f = f + f2
1046 t = t + t2
1047 self.name2ft[name] = f, t
1048
1049 def __runone(self, target, name):
1050 if "." in name:
Eric S. Raymond630e69c2001-02-09 08:33:43 +00001051 i = name.rindex(".")
Tim Peters8a7d2d52001-01-16 07:10:57 +00001052 prefix, base = name[:i], name[i+1:]
1053 else:
1054 prefix, base = "", base
1055 if self.isprivate(prefix, base):
1056 return 0, 0
1057 return self.rundoc(target, name)
1058
1059master = None
1060
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001061def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
Tim Peters6ebe61f2003-06-27 20:48:05 +00001062 report=True, optionflags=0):
1063 """m=None, name=None, globs=None, verbose=None, isprivate=None,
1064 report=True, optionflags=0
Tim Peters8a7d2d52001-01-16 07:10:57 +00001065
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001066 Test examples in docstrings in functions and classes reachable
1067 from module m (or the current module if m is not supplied), starting
1068 with m.__doc__. Private names are skipped.
Tim Peters8a7d2d52001-01-16 07:10:57 +00001069
1070 Also test examples reachable from dict m.__test__ if it exists and is
1071 not None. m.__dict__ maps names to functions, classes and strings;
1072 function and class docstrings are tested even if the name is private;
1073 strings are tested directly, as if they were docstrings.
1074
1075 Return (#failures, #tests).
1076
1077 See doctest.__doc__ for an overview.
1078
1079 Optional keyword arg "name" gives the name of the module; by default
1080 use m.__name__.
1081
1082 Optional keyword arg "globs" gives a dict to be used as the globals
1083 when executing examples; by default, use m.__dict__. A copy of this
1084 dict is actually used for each docstring, so that each docstring's
1085 examples start with a clean slate.
1086
1087 Optional keyword arg "verbose" prints lots of stuff if true, prints
1088 only failures if false; by default, it's true iff "-v" is in sys.argv.
1089
1090 Optional keyword arg "isprivate" specifies a function used to
1091 determine whether a name is private. The default function is
1092 doctest.is_private; see its docs for details.
1093
1094 Optional keyword arg "report" prints a summary at the end when true,
1095 else prints nothing at the end. In verbose mode, the summary is
1096 detailed, else very brief (in fact, empty if all tests passed).
1097
Tim Peters6ebe61f2003-06-27 20:48:05 +00001098 Optional keyword arg "optionflags" or's together module constants,
1099 and defaults to 0. This is new in 2.3. Possible values:
1100
1101 DONT_ACCEPT_TRUE_FOR_1
1102 By default, if an expected output block contains just "1",
1103 an actual output block containing just "True" is considered
1104 to be a match, and similarly for "0" versus "False". When
1105 DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution
1106 is allowed.
1107
Tim Peters8a7d2d52001-01-16 07:10:57 +00001108 Advanced tomfoolery: testmod runs methods of a local instance of
1109 class doctest.Tester, then merges the results into (or creates)
1110 global Tester instance doctest.master. Methods of doctest.master
1111 can be called directly too, if you want to do something unusual.
1112 Passing report=0 to testmod is especially useful then, to delay
1113 displaying a summary. Invoke doctest.master.summarize(verbose)
1114 when you're done fiddling.
1115 """
1116
1117 global master
1118
Martin v. Löwis4581cfa2002-11-22 08:23:09 +00001119 if m is None:
1120 import sys
1121 # DWA - m will still be None if this wasn't invoked from the command
1122 # line, in which case the following TypeError is about as good an error
1123 # as we should expect
1124 m = sys.modules.get('__main__')
1125
Tim Peters7402f792001-10-02 03:53:41 +00001126 if not _ismodule(m):
Tim Peters8a7d2d52001-01-16 07:10:57 +00001127 raise TypeError("testmod: module required; " + `m`)
1128 if name is None:
1129 name = m.__name__
Tim Peters6ebe61f2003-06-27 20:48:05 +00001130 tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate,
1131 optionflags=optionflags)
Tim Peters8a7d2d52001-01-16 07:10:57 +00001132 failures, tries = tester.rundoc(m, name)
Tim Peters4a9ac4a2001-10-02 22:47:08 +00001133 f, t = tester.rundict(m.__dict__, name, m)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001134 failures += f
1135 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001136 if hasattr(m, "__test__"):
1137 testdict = m.__test__
1138 if testdict:
1139 if not hasattr(testdict, "items"):
1140 raise TypeError("testmod: module.__test__ must support "
1141 ".items(); " + `testdict`)
1142 f, t = tester.run__test__(testdict, name + ".__test__")
Tim Peters6ebe61f2003-06-27 20:48:05 +00001143 failures += f
1144 tries += t
Tim Peters8a7d2d52001-01-16 07:10:57 +00001145 if report:
1146 tester.summarize()
1147 if master is None:
1148 master = tester
1149 else:
1150 master.merge(tester)
1151 return failures, tries
1152
1153class _TestClass:
1154 """
1155 A pointless class, for sanity-checking of docstring testing.
1156
1157 Methods:
1158 square()
1159 get()
1160
1161 >>> _TestClass(13).get() + _TestClass(-12).get()
1162 1
1163 >>> hex(_TestClass(13).square().get())
1164 '0xa9'
1165 """
1166
1167 def __init__(self, val):
1168 """val -> _TestClass object with associated value val.
1169
1170 >>> t = _TestClass(123)
1171 >>> print t.get()
1172 123
1173 """
1174
1175 self.val = val
1176
1177 def square(self):
1178 """square() -> square TestClass's associated value
1179
1180 >>> _TestClass(13).square().get()
1181 169
1182 """
1183
1184 self.val = self.val ** 2
1185 return self
1186
1187 def get(self):
1188 """get() -> return TestClass's associated value.
1189
1190 >>> x = _TestClass(-42)
1191 >>> print x.get()
1192 -42
1193 """
1194
1195 return self.val
1196
1197__test__ = {"_TestClass": _TestClass,
1198 "string": r"""
1199 Example of a string object, searched as-is.
1200 >>> x = 1; y = 2
1201 >>> x + y, x * y
1202 (3, 2)
Tim Peters6ebe61f2003-06-27 20:48:05 +00001203 """,
1204 "bool-int equivalence": r"""
1205 In 2.2, boolean expressions displayed
1206 0 or 1. By default, we still accept
1207 them. This can be disabled by passing
1208 DONT_ACCEPT_TRUE_FOR_1 to the new
1209 optionflags argument.
1210 >>> 4 == 4
1211 1
1212 >>> 4 == 4
1213 True
1214 >>> 4 > 4
1215 0
1216 >>> 4 > 4
1217 False
1218 """,
Tim Peters8a7d2d52001-01-16 07:10:57 +00001219 }
1220
1221def _test():
1222 import doctest
1223 return doctest.testmod(doctest)
1224
1225if __name__ == "__main__":
1226 _test()