~ubuntu-branches/ubuntu/wily/python-imaging/wily

« back to all changes in this revision

Viewing changes to doctest.py

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2013-01-31 20:49:20 UTC
  • mfrom: (1.1.4)
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130131204920-7tnuhqhlsqdza4c2
Rewrite build dependencies to allow cross builds.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Module doctest version 0.9.6
2
 
# Released to the public domain 16-Jan-2001,
3
 
# by Tim Peters (tim.one@home.com).
4
 
 
5
 
# local modifications:
6
 
# 2001-02-13 fl: minor tweaks to make it run under both 1.5.2 and 2.0
7
 
 
8
 
# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
9
 
 
10
 
"""Module doctest -- a framework for running examples in docstrings.
11
 
 
12
 
NORMAL USAGE
13
 
 
14
 
In normal use, end each module M with:
15
 
 
16
 
def _test():
17
 
    import doctest, M           # replace M with your module's name
18
 
    return doctest.testmod(M)   # ditto
19
 
 
20
 
if __name__ == "__main__":
21
 
    _test()
22
 
 
23
 
Then running the module as a script will cause the examples in the
24
 
docstrings to get executed and verified:
25
 
 
26
 
python M.py
27
 
 
28
 
This won't display anything unless an example fails, in which case the
29
 
failing example(s) and the cause(s) of the failure(s) are printed to stdout
30
 
(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
31
 
line of output is "Test failed.".
32
 
 
33
 
Run it with the -v switch instead:
34
 
 
35
 
python M.py -v
36
 
 
37
 
and a detailed report of all examples tried is printed to stdout, along
38
 
with assorted summaries at the end.
39
 
 
40
 
You can force verbose mode by passing "verbose=1" to testmod, or prohibit
41
 
it by passing "verbose=0".  In either of those cases, sys.argv is not
42
 
examined by testmod.
43
 
 
44
 
In any case, testmod returns a 2-tuple of ints (f, t), where f is the
45
 
number of docstring examples that failed and t is the total number of
46
 
docstring examples attempted.
47
 
 
48
 
 
49
 
WHICH DOCSTRINGS ARE EXAMINED?
50
 
 
51
 
+ M.__doc__.
52
 
 
53
 
+ f.__doc__ for all functions f in M.__dict__.values(), except those
54
 
  with private names.
55
 
 
56
 
+ C.__doc__ for all classes C in M.__dict__.values(), except those with
57
 
  private names.
58
 
 
59
 
+ If M.__test__ exists and "is true", it must be a dict, and
60
 
  each entry maps a (string) name to a function object, class object, or
61
 
  string.  Function and class object docstrings found from M.__test__
62
 
  are searched even if the name is private, and strings are searched
63
 
  directly as if they were docstrings.  In output, a key K in M.__test__
64
 
  appears with name
65
 
      <name of M>.__test__.K
66
 
 
67
 
Any classes found are recursively searched similarly, to test docstrings in
68
 
their contained methods and nested classes.  Private names reached from M's
69
 
globals are skipped, but all names reached from M.__test__ are searched.
70
 
 
71
 
By default, a name is considered to be private if it begins with an
72
 
underscore (like "_my_func") but doesn't both begin and end with (at least)
73
 
two underscores (like "__init__").  You can change the default by passing
74
 
your own "isprivate" function to testmod.
75
 
 
76
 
If you want to test docstrings in objects with private names too, stuff
77
 
them into an M.__test__ dict, or see ADVANCED USAGE below (e.g., pass your
78
 
own isprivate function to Tester's constructor, or call the rundoc method
79
 
of a Tester instance).
80
 
 
81
 
Warning:  imports can cause trouble; e.g., if you do
82
 
 
83
 
from XYZ import XYZclass
84
 
 
85
 
then XYZclass is a name in M.__dict__ too, and doctest has no way to know
86
 
that XYZclass wasn't *defined* in M.  So it may try to execute the examples
87
 
in XYZclass's docstring, and those in turn may require a different set of
88
 
globals to work correctly.  I prefer to do "import *"- friendly imports,
89
 
a la
90
 
 
91
 
import XYY
92
 
_XYZclass = XYZ.XYZclass
93
 
del XYZ
94
 
 
95
 
or (Python 2.0)
96
 
 
97
 
from XYZ import XYZclass as _XYZclass
98
 
 
99
 
and then the leading underscore stops testmod from going nuts.  You may
100
 
prefer the method in the next section.
101
 
 
102
 
 
103
 
WHAT'S THE EXECUTION CONTEXT?
104
 
 
105
 
By default, each time testmod finds a docstring to test, it uses a *copy*
106
 
of M's globals (so that running tests on a module doesn't change the
107
 
module's real globals, and so that one test in M can't leave behind crumbs
108
 
that accidentally allow another test to work).  This means examples can
109
 
freely use any names defined at top-level in M.  It also means that sloppy
110
 
imports (see above) can cause examples in external docstrings to use
111
 
globals inappropriate for them.
112
 
 
113
 
You can force use of your own dict as the execution context by passing
114
 
"globs=your_dict" to testmod instead.  Presumably this would be a copy of
115
 
M.__dict__ merged with the globals from other imported modules.
116
 
 
117
 
 
118
 
WHAT IF I WANT TO TEST A WHOLE PACKAGE?
119
 
 
120
 
Piece o' cake, provided the modules do their testing from docstrings.
121
 
Here's the test.py I use for the world's most elaborate Rational/
122
 
floating-base-conversion pkg (which I'll distribute some day):
123
 
 
124
 
from Rational import Cvt
125
 
from Rational import Format
126
 
from Rational import machprec
127
 
from Rational import Rat
128
 
from Rational import Round
129
 
from Rational import utils
130
 
 
131
 
modules = (Cvt,
132
 
           Format,
133
 
           machprec,
134
 
           Rat,
135
 
           Round,
136
 
           utils)
137
 
 
138
 
def _test():
139
 
    import doctest
140
 
    import sys
141
 
    verbose = "-v" in sys.argv
142
 
    for mod in modules:
143
 
        doctest.testmod(mod, verbose=verbose, report=0)
144
 
    doctest.master.summarize()
145
 
 
146
 
if __name__ == "__main__":
147
 
    _test()
148
 
 
149
 
IOW, it just runs testmod on all the pkg modules.  testmod remembers the
150
 
names and outcomes (# of failures, # of tries) for each item it's seen, and
151
 
passing "report=0" prevents it from printing a summary in verbose mode.
152
 
Instead, the summary is delayed until all modules have been tested, and
153
 
then "doctest.master.summarize()" forces the summary at the end.
154
 
 
155
 
So this is very nice in practice:  each module can be tested individually
156
 
with almost no work beyond writing up docstring examples, and collections
157
 
of modules can be tested too as a unit with no more work than the above.
158
 
 
159
 
 
160
 
WHAT ABOUT EXCEPTIONS?
161
 
 
162
 
No problem, as long as the only output generated by the example is the
163
 
traceback itself.  For example:
164
 
 
165
 
    >>> a = [None]
166
 
    >>> a[1]
167
 
    Traceback (innermost last):
168
 
      File "<stdin>", line 1, in ?
169
 
    IndexError: list index out of range
170
 
    >>>
171
 
 
172
 
Note that only the exception type and value are compared (specifically,
173
 
only the last line in the traceback).
174
 
 
175
 
 
176
 
ADVANCED USAGE
177
 
 
178
 
doctest.testmod() captures the testing policy I find most useful most
179
 
often.  You may want other policies.
180
 
 
181
 
testmod() actually creates a local instance of class doctest.Tester, runs
182
 
appropriate methods of that class, and merges the results into global
183
 
Tester instance doctest.master.
184
 
 
185
 
You can create your own instances of doctest.Tester, and so build your own
186
 
policies, or even run methods of doctest.master directly.  See
187
 
doctest.Tester.__doc__ for details.
188
 
 
189
 
 
190
 
SO WHAT DOES A DOCSTRING EXAMPLE LOOK LIKE ALREADY!?
191
 
 
192
 
Oh ya.  It's easy!  In most cases a copy-and-paste of an interactive
193
 
console session works fine -- just make sure the leading whitespace is
194
 
rigidly consistent (you can mix tabs and spaces if you're too lazy to do it
195
 
right, but doctest is not in the business of guessing what you think a tab
196
 
means).
197
 
 
198
 
    >>> # comments are ignored
199
 
    >>> x = 12
200
 
    >>> x
201
 
    12
202
 
    >>> if x == 13:
203
 
    ...     print "yes"
204
 
    ... else:
205
 
    ...     print "no"
206
 
    ...     print "NO"
207
 
    ...     print "NO!!!"
208
 
    ...
209
 
    no
210
 
    NO
211
 
    NO!!!
212
 
    >>>
213
 
 
214
 
Any expected output must immediately follow the final ">>>" or "..." line
215
 
containing the code, and the expected output (if any) extends to the next
216
 
">>>" or all-whitespace line.  That's it.
217
 
 
218
 
Bummers:
219
 
 
220
 
+ Expected output cannot contain an all-whitespace line, since such a line
221
 
  is taken to signal the end of expected output.
222
 
 
223
 
+ Output to stdout is captured, but not output to stderr (exception
224
 
  tracebacks are captured via a different means).
225
 
 
226
 
+ If you continue a line via backslashing in an interactive session, or for
227
 
  any other reason use a backslash, you need to double the backslash in the
228
 
  docstring version.  This is simply because you're in a string, and so the
229
 
  backslash must be escaped for it to survive intact.  Like:
230
 
 
231
 
>>> if "yes" == \\
232
 
...     "y" +   \\
233
 
...     "es":   # in the source code you'll see the doubled backslashes
234
 
...     print 'yes'
235
 
yes
236
 
 
237
 
The starting column doesn't matter:
238
 
 
239
 
>>> assert "Easy!"
240
 
     >>> import math
241
 
            >>> math.floor(1.9)
242
 
            1.0
243
 
 
244
 
and as many leading whitespace characters are stripped from the expected
245
 
output as appeared in the initial ">>>" line that triggered it.
246
 
 
247
 
If you execute this very file, the examples above will be found and
248
 
executed, leading to this output in verbose mode:
249
 
 
250
 
Running doctest.__doc__
251
 
Trying: a = [None]
252
 
Expecting: nothing
253
 
ok
254
 
Trying: a[1]
255
 
Expecting:
256
 
Traceback (innermost last):
257
 
  File "<stdin>", line 1, in ?
258
 
IndexError: list index out of range
259
 
ok
260
 
Trying: x = 12
261
 
Expecting: nothing
262
 
ok
263
 
Trying: x
264
 
Expecting: 12
265
 
ok
266
 
Trying:
267
 
if x == 13:
268
 
    print "yes"
269
 
else:
270
 
    print "no"
271
 
    print "NO"
272
 
    print "NO!!!"
273
 
Expecting:
274
 
no
275
 
NO
276
 
NO!!!
277
 
ok
278
 
... and a bunch more like that, with this summary at the end:
279
 
 
280
 
5 items had no tests:
281
 
    doctest.Tester.__init__
282
 
    doctest.Tester.run__test__
283
 
    doctest.Tester.summarize
284
 
    doctest.run_docstring_examples
285
 
    doctest.testmod
286
 
12 items passed all tests:
287
 
   9 tests in doctest
288
 
   6 tests in doctest.Tester
289
 
  10 tests in doctest.Tester.merge
290
 
   7 tests in doctest.Tester.rundict
291
 
   3 tests in doctest.Tester.rundoc
292
 
   3 tests in doctest.Tester.runstring
293
 
   2 tests in doctest.__test__._TestClass
294
 
   2 tests in doctest.__test__._TestClass.__init__
295
 
   2 tests in doctest.__test__._TestClass.get
296
 
   1 tests in doctest.__test__._TestClass.square
297
 
   2 tests in doctest.__test__.string
298
 
   7 tests in doctest.is_private
299
 
54 tests in 17 items.
300
 
54 passed and 0 failed.
301
 
Test passed.
302
 
"""
303
 
 
304
 
# 0,0,1    06-Mar-1999
305
 
#    initial version posted
306
 
# 0,0,2    06-Mar-1999
307
 
#    loosened parsing:
308
 
#        cater to stinkin' tabs
309
 
#        don't insist on a blank after PS2 prefix
310
 
#            so trailing "... " line from a compound stmt no longer
311
 
#            breaks if the file gets whitespace-trimmed
312
 
#    better error msgs for inconsistent leading whitespace
313
 
# 0,9,1    08-Mar-1999
314
 
#    exposed the Tester class and added client methods
315
 
#        plus docstring examples of their use (eww - head-twisting!)
316
 
#    fixed logic error in reporting total # of tests & failures
317
 
#    added __test__ support to testmod (a pale reflection of Christian
318
 
#        Tismer's vision ...)
319
 
#    removed the "deep" argument; fiddle __test__ instead
320
 
#    simplified endcase logic for extracting tests, and running them.
321
 
#        before, if no output was expected but some was produced
322
 
#        anyway via an eval'ed result, the discrepancy wasn't caught
323
 
#    made TestClass private and used __test__ to get at it
324
 
#    many doc updates
325
 
#    speed _SpoofOut for long expected outputs
326
 
# 0,9,2    09-Mar-1999
327
 
#    throw out comments from examples, enabling use of the much simpler
328
 
#        exec compile(... "single") ...
329
 
#        for simulating the runtime; that barfs on comment-only lines
330
 
#    used the traceback module to do a much better job of reporting
331
 
#        exceptions
332
 
#    run __doc__ values thru str(), "just in case"
333
 
#    privateness of names now determined by an overridable "isprivate"
334
 
#        function
335
 
#    by default a name now considered to be private iff it begins with
336
 
#        an underscore but doesn't both begin & end with two of 'em; so
337
 
#        e.g. Class.__init__ etc are searched now -- as they always
338
 
#        should have been
339
 
# 0,9,3    18-Mar-1999
340
 
#    added .flush stub to _SpoofOut (JPython buglet diagnosed by
341
 
#        Hugh Emberson)
342
 
#    repaired ridiculous docs about backslashes in examples
343
 
#    minor internal changes
344
 
#    changed source to Unix line-end conventions
345
 
#    moved __test__ logic into new Tester.run__test__ method
346
 
# 0,9,4    27-Mar-1999
347
 
#    report item name and line # in failing examples
348
 
# 0,9,5    29-Jun-1999
349
 
#    allow straightforward exceptions in examples - thanks to Mark Hammond!
350
 
# 0,9,6    16-Jan-2001
351
 
#    fiddling for changes in Python 2.0:  some of the embedded docstring
352
 
#        examples no longer worked *exactly* as advertised, due to minor
353
 
#        language changes, and running doctest on itself pointed that out.
354
 
#        Hard to think of a better example of why this is useful <wink>.
355
 
 
356
 
__version__ = 0, 9, 6
357
 
 
358
 
import types
359
 
_FunctionType = types.FunctionType
360
 
_ClassType    = types.ClassType
361
 
_ModuleType   = types.ModuleType
362
 
_StringType   = types.StringType
363
 
del types
364
 
 
365
 
import string
366
 
_string_find = string.find
367
 
_string_join = string.join
368
 
_string_split = string.split
369
 
_string_rindex = string.rindex
370
 
del string
371
 
 
372
 
import re
373
 
PS1 = ">>>"
374
 
PS2 = "..."
375
 
_isPS1 = re.compile(r"(\s*)" + re.escape(PS1)).match
376
 
_isPS2 = re.compile(r"(\s*)" + re.escape(PS2)).match
377
 
_isEmpty = re.compile(r"\s*$").match
378
 
_isComment = re.compile(r"\s*#").match
379
 
del re
380
 
 
381
 
__all__ = []
382
 
 
383
 
# Extract interactive examples from a string.  Return a list of triples,
384
 
# (source, outcome, lineno).  "source" is the source code, and ends
385
 
# with a newline iff the source spans more than one line.  "outcome" is
386
 
# the expected output if any, else an empty string.  When not empty,
387
 
# outcome always ends with a newline.  "lineno" is the line number,
388
 
# 0-based wrt the start of the string, of the first source line.
389
 
 
390
 
def _extract_examples(s):
391
 
    isPS1, isPS2 = _isPS1, _isPS2
392
 
    isEmpty, isComment = _isEmpty, _isComment
393
 
    examples = []
394
 
    lines = _string_split(s, "\n")
395
 
    i, n = 0, len(lines)
396
 
    while i < n:
397
 
        line = lines[i]
398
 
        i = i + 1
399
 
        m = isPS1(line)
400
 
        if m is None:
401
 
            continue
402
 
        j = m.end(0)  # beyond the prompt
403
 
        if isEmpty(line, j) or isComment(line, j):
404
 
            # a bare prompt or comment -- not interesting
405
 
            continue
406
 
        lineno = i - 1
407
 
        if line[j] != " ":
408
 
            raise ValueError("line " + `lineno` + " of docstring lacks "
409
 
                "blank after " + PS1 + ": " + line)
410
 
        j = j + 1
411
 
        blanks = m.group(1)
412
 
        nblanks = len(blanks)
413
 
        # suck up this and following PS2 lines
414
 
        source = []
415
 
        while 1:
416
 
            source.append(line[j:])
417
 
            line = lines[i]
418
 
            m = isPS2(line)
419
 
            if m:
420
 
                if m.group(1) != blanks:
421
 
                    raise ValueError("inconsistent leading whitespace "
422
 
                        "in line " + `i` + " of docstring: " + line)
423
 
                i = i + 1
424
 
            else:
425
 
                break
426
 
        if len(source) == 1:
427
 
            source = source[0]
428
 
        else:
429
 
            # get rid of useless null line from trailing empty "..."
430
 
            if source[-1] == "":
431
 
                del source[-1]
432
 
            source = _string_join(source, "\n") + "\n"
433
 
        # suck up response
434
 
        if isPS1(line) or isEmpty(line):
435
 
            expect = ""
436
 
        else:
437
 
            expect = []
438
 
            while 1:
439
 
                if line[:nblanks] != blanks:
440
 
                    raise ValueError("inconsistent leading whitespace "
441
 
                        "in line " + `i` + " of docstring: " + line)
442
 
                expect.append(line[nblanks:])
443
 
                i = i + 1
444
 
                line = lines[i]
445
 
                if isPS1(line) or isEmpty(line):
446
 
                    break
447
 
            expect = _string_join(expect, "\n") + "\n"
448
 
        examples.append( (source, expect, lineno) )
449
 
    return examples
450
 
 
451
 
# Capture stdout when running examples.
452
 
 
453
 
class _SpoofOut:
454
 
    def __init__(self):
455
 
        self.clear()
456
 
    def write(self, s):
457
 
        self.buf.append(s)
458
 
    def get(self):
459
 
        return _string_join(self.buf, "")
460
 
    def clear(self):
461
 
        self.buf = []
462
 
    def flush(self):
463
 
        # JPython calls flush
464
 
        pass
465
 
 
466
 
# Display some tag-and-msg pairs nicely, keeping the tag and its msg
467
 
# on the same line when that makes sense.
468
 
 
469
 
def _tag_out(printer, *tag_msg_pairs):
470
 
    for tag, msg in tag_msg_pairs:
471
 
        printer(tag + ":")
472
 
        msg_has_nl = msg[-1:] == "\n"
473
 
        msg_has_two_nl = msg_has_nl and \
474
 
                        _string_find(msg, "\n") < len(msg) - 1
475
 
        if len(tag) + len(msg) < 76 and not msg_has_two_nl:
476
 
            printer(" ")
477
 
        else:
478
 
            printer("\n")
479
 
        printer(msg)
480
 
        if not msg_has_nl:
481
 
            printer("\n")
482
 
 
483
 
# Run list of examples, in context globs.  "out" can be used to display
484
 
# stuff to "the real" stdout, and fakeout is an instance of _SpoofOut
485
 
# that captures the examples' std output.  Return (#failures, #tries).
486
 
 
487
 
def _run_examples_inner(out, fakeout, examples, globs, verbose, name):
488
 
    import sys, traceback
489
 
    OK, BOOM, FAIL = range(3)
490
 
    NADA = "nothing"
491
 
    stderr = _SpoofOut()
492
 
    failures = 0
493
 
    for source, want, lineno in examples:
494
 
        if verbose:
495
 
            _tag_out(out, ("Trying", source),
496
 
                          ("Expecting", want or NADA))
497
 
        fakeout.clear()
498
 
        try:
499
 
            exec compile(source, "<string>", "single") in globs
500
 
            got = fakeout.get()
501
 
            state = OK
502
 
        except:
503
 
            # See whether the exception was expected.
504
 
            if _string_find(want, "Traceback (innermost last):\n") == 0 or\
505
 
               _string_find(want, "Traceback (most recent call last):\n") == 0:
506
 
                # Only compare exception type and value - the rest of
507
 
                # the traceback isn't necessary.
508
 
                want = _string_split(want, '\n')[-2] + '\n'
509
 
                exc_type, exc_val, exc_tb = sys.exc_info()
510
 
                got = traceback.format_exception_only(exc_type, exc_val)[0]
511
 
                state = OK
512
 
            else:
513
 
                # unexpected exception
514
 
                stderr.clear()
515
 
                traceback.print_exc(file=stderr)
516
 
                state = BOOM
517
 
 
518
 
        if state == OK:
519
 
            if got == want:
520
 
                if verbose:
521
 
                    out("ok\n")
522
 
                continue
523
 
            state = FAIL
524
 
 
525
 
        assert state in (FAIL, BOOM)
526
 
        failures = failures + 1
527
 
        out("*" * 65 + "\n")
528
 
        _tag_out(out, ("Failure in example", source))
529
 
        out("from line #" + `lineno` + " of " + name + "\n")
530
 
        if state == FAIL:
531
 
            _tag_out(out, ("Expected", want or NADA), ("Got", got))
532
 
        else:
533
 
            assert state == BOOM
534
 
            _tag_out(out, ("Exception raised", stderr.get()))
535
 
 
536
 
    return failures, len(examples)
537
 
 
538
 
# Run list of examples, in context globs.  Return (#failures, #tries).
539
 
 
540
 
def _run_examples(examples, globs, verbose, name):
541
 
    import sys
542
 
    saveout = sys.stdout
543
 
    try:
544
 
        sys.stdout = fakeout = _SpoofOut()
545
 
        x = _run_examples_inner(saveout.write, fakeout, examples,
546
 
                                globs, verbose, name)
547
 
    finally:
548
 
        sys.stdout = saveout
549
 
    return x
550
 
 
551
 
def run_docstring_examples(f, globs, verbose=0, name="NoName"):
552
 
    """f, globs, verbose=0, name="NoName" -> run examples from f.__doc__.
553
 
 
554
 
    Use dict globs as the globals for execution.
555
 
    Return (#failures, #tries).
556
 
 
557
 
    If optional arg verbose is true, print stuff even if there are no
558
 
    failures.
559
 
    Use string name in failure msgs.
560
 
    """
561
 
 
562
 
    try:
563
 
        doc = f.__doc__
564
 
        if not doc:
565
 
            # docstring empty or None
566
 
            return 0, 0
567
 
        # just in case CT invents a doc object that has to be forced
568
 
        # to look like a string <0.9 wink>
569
 
        doc = str(doc)
570
 
    except:
571
 
        return 0, 0
572
 
 
573
 
    e = _extract_examples(doc)
574
 
    if not e:
575
 
        return 0, 0
576
 
    return _run_examples(e, globs, verbose, name)
577
 
 
578
 
def is_private(prefix, base):
579
 
    """prefix, base -> true iff name prefix + "." + base is "private".
580
 
 
581
 
    Prefix may be an empty string, and base does not contain a period.
582
 
    Prefix is ignored (although functions you write conforming to this
583
 
    protocol may make use of it).
584
 
    Return true iff base begins with an (at least one) underscore, but
585
 
    does not both begin and end with (at least) two underscores.
586
 
 
587
 
    >>> is_private("a.b", "my_func")
588
 
    0
589
 
    >>> is_private("____", "_my_func")
590
 
    1
591
 
    >>> is_private("someclass", "__init__")
592
 
    0
593
 
    >>> is_private("sometypo", "__init_")
594
 
    1
595
 
    >>> is_private("x.y.z", "_")
596
 
    1
597
 
    >>> is_private("_x.y.z", "__")
598
 
    0
599
 
    >>> is_private("", "")  # senseless but consistent
600
 
    0
601
 
    """
602
 
 
603
 
    return base[:1] == "_" and not base[:2] == "__" == base[-2:]
604
 
 
605
 
class Tester:
606
 
    """Class Tester -- runs docstring examples and accumulates stats.
607
 
 
608
 
In normal use, function doctest.testmod() hides all this from you,
609
 
so use that if you can.  Create your own instances of Tester to do
610
 
fancier things.
611
 
 
612
 
Methods:
613
 
    runstring(s, name)
614
 
        Search string s for examples to run; use name for logging.
615
 
        Return (#failures, #tries).
616
 
 
617
 
    rundoc(object, name=None)
618
 
        Search object.__doc__ for examples to run; use name (or
619
 
        object.__name__) for logging.  Return (#failures, #tries).
620
 
 
621
 
    rundict(d, name)
622
 
        Search for examples in docstrings in all of d.values(); use name
623
 
        for logging.  Return (#failures, #tries).
624
 
 
625
 
    run__test__(d, name)
626
 
        Treat dict d like module.__test__.  Return (#failures, #tries).
627
 
 
628
 
    summarize(verbose=None)
629
 
        Display summary of testing results, to stdout.  Return
630
 
        (#failures, #tries).
631
 
 
632
 
    merge(other)
633
 
        Merge in the test results from Tester instance "other".
634
 
 
635
 
>>> from doctest import Tester
636
 
>>> t = Tester(globs={'x': 42}, verbose=0)
637
 
>>> t.runstring(r'''
638
 
...      >>> x = x * 2
639
 
...      >>> print x
640
 
...      42
641
 
... ''', 'XYZ')
642
 
*****************************************************************
643
 
Failure in example: print x
644
 
from line #2 of XYZ
645
 
Expected: 42
646
 
Got: 84
647
 
(1, 2)
648
 
>>> t.runstring(">>> x = x * 2\\n>>> print x\\n84\\n", 'example2')
649
 
(0, 2)
650
 
>>> t.summarize()
651
 
1 items had failures:
652
 
   1 of   2 in XYZ
653
 
***Test Failed*** 1 failures.
654
 
(1, 4)
655
 
>>> t.summarize(verbose=1)
656
 
1 items passed all tests:
657
 
   2 tests in example2
658
 
1 items had failures:
659
 
   1 of   2 in XYZ
660
 
4 tests in 2 items.
661
 
3 passed and 1 failed.
662
 
***Test Failed*** 1 failures.
663
 
(1, 4)
664
 
>>>
665
 
"""
666
 
 
667
 
    def __init__(self, mod=None, globs=None, verbose=None,
668
 
                 isprivate=None):
669
 
        """mod=None, globs=None, verbose=None, isprivate=None
670
 
 
671
 
See doctest.__doc__ for an overview.
672
 
 
673
 
Optional keyword arg "mod" is a module, whose globals are used for
674
 
executing examples.  If not specified, globs must be specified.
675
 
 
676
 
Optional keyword arg "globs" gives a dict to be used as the globals
677
 
when executing examples; if not specified, use the globals from
678
 
module mod.
679
 
 
680
 
In either case, a copy of the dict is used for each docstring
681
 
examined.
682
 
 
683
 
Optional keyword arg "verbose" prints lots of stuff if true, only
684
 
failures if false; by default, it's true iff "-v" is in sys.argv.
685
 
 
686
 
Optional keyword arg "isprivate" specifies a function used to determine
687
 
whether a name is private.  The default function is doctest.is_private;
688
 
see its docs for details.
689
 
"""
690
 
 
691
 
        if mod is None and globs is None:
692
 
            raise TypeError("Tester.__init__: must specify mod or globs")
693
 
        if mod is not None and type(mod) is not _ModuleType:
694
 
            raise TypeError("Tester.__init__: mod must be a module; " +
695
 
                            `mod`)
696
 
        if globs is None:
697
 
            globs = mod.__dict__
698
 
        self.globs = globs
699
 
 
700
 
        if verbose is None:
701
 
            import sys
702
 
            verbose = "-v" in sys.argv
703
 
        self.verbose = verbose
704
 
 
705
 
        if isprivate is None:
706
 
            isprivate = is_private
707
 
        self.isprivate = isprivate
708
 
 
709
 
        self.name2ft = {}   # map name to (#failures, #trials) pair
710
 
 
711
 
    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:
742
 
            f, t = _run_examples(e, self.globs.copy(), self.verbose, name)
743
 
        if self.verbose:
744
 
            print f, "of", t, "examples failed in string", name
745
 
        self.__record_outcome(name, f, t)
746
 
        return f, t
747
 
 
748
 
    def rundoc(self, object, name=None):
749
 
        """
750
 
        object, name=None -> search object.__doc__ for examples to run.
751
 
 
752
 
        Use optional string name as the key for logging the outcome;
753
 
        by default use object.__name__.
754
 
        Return (#failures, #examples).
755
 
        If object is a class object, search recursively for method
756
 
        docstrings too.
757
 
        object.__doc__ is examined regardless of name, but if object is
758
 
        a class, whether private names reached from object are searched
759
 
        depends on the constructor's "isprivate" argument.
760
 
 
761
 
        >>> t = Tester(globs={}, verbose=0)
762
 
        >>> def _f():
763
 
        ...     '''Trivial docstring example.
764
 
        ...     >>> assert 2 == 2
765
 
        ...     '''
766
 
        ...     return 32
767
 
        ...
768
 
        >>> t.rundoc(_f)  # expect 0 failures in 1 example
769
 
        (0, 1)
770
 
        """
771
 
 
772
 
        if name is None:
773
 
            try:
774
 
                name = object.__name__
775
 
            except AttributeError:
776
 
                raise ValueError("Tester.rundoc: name must be given "
777
 
                    "when object.__name__ doesn't exist; " + `object`)
778
 
        if self.verbose:
779
 
            print "Running", name + ".__doc__"
780
 
        f, t = run_docstring_examples(object, self.globs.copy(),
781
 
                                      self.verbose, name)
782
 
        if self.verbose:
783
 
            print f, "of", t, "examples failed in", name + ".__doc__"
784
 
        self.__record_outcome(name, f, t)
785
 
        if type(object) is _ClassType:
786
 
            f2, t2 = self.rundict(object.__dict__, name)
787
 
            f = f + f2
788
 
            t = t + t2
789
 
        return f, t
790
 
 
791
 
    def rundict(self, d, name):
792
 
        """
793
 
        d. name -> search for docstring examples in all of d.values().
794
 
 
795
 
        For k, v in d.items() such that v is a function or class,
796
 
        do self.rundoc(v, name + "." + k).  Whether this includes
797
 
        objects with private names depends on the constructor's
798
 
        "isprivate" argument.
799
 
        Return aggregate (#failures, #examples).
800
 
 
801
 
        >>> def _f():
802
 
        ...    '''>>> assert 1 == 1
803
 
        ...    '''
804
 
        >>> def g():
805
 
        ...    '''>>> assert 2 != 1
806
 
        ...    '''
807
 
        >>> d = {"_f": _f, "g": g}
808
 
        >>> t = Tester(globs={}, verbose=0)
809
 
        >>> t.rundict(d, "rundict_test")  # _f is skipped
810
 
        (0, 1)
811
 
        >>> t = Tester(globs={}, verbose=0, isprivate=lambda x,y: 0)
812
 
        >>> t.rundict(d, "rundict_test_pvt")  # both are searched
813
 
        (0, 2)
814
 
        """
815
 
 
816
 
        if not hasattr(d, "items"):
817
 
            raise TypeError("Tester.rundict: d must support .items(); " +
818
 
                            `d`)
819
 
        f = t = 0
820
 
        for thisname, value in d.items():
821
 
            if type(value) in (_FunctionType, _ClassType):
822
 
                f2, t2 = self.__runone(value, name + "." + thisname)
823
 
                f = f + f2
824
 
                t = t + t2
825
 
        return f, t
826
 
 
827
 
    def run__test__(self, d, name):
828
 
        """d, name -> Treat dict d like module.__test__.
829
 
 
830
 
        Return (#failures, #tries).
831
 
        See testmod.__doc__ for details.
832
 
        """
833
 
 
834
 
        failures = tries = 0
835
 
        prefix = name + "."
836
 
        savepvt = self.isprivate
837
 
        try:
838
 
            self.isprivate = lambda *args: 0
839
 
            for k, v in d.items():
840
 
                thisname = prefix + k
841
 
                if type(v) is _StringType:
842
 
                    f, t = self.runstring(v, thisname)
843
 
                elif type(v) in (_FunctionType, _ClassType):
844
 
                    f, t = self.rundoc(v, thisname)
845
 
                else:
846
 
                    raise TypeError("Tester.run__test__: values in "
847
 
                            "dict must be strings, functions "
848
 
                            "or classes; " + `v`)
849
 
                failures = failures + f
850
 
                tries = tries + t
851
 
        finally:
852
 
            self.isprivate = savepvt
853
 
        return failures, tries
854
 
 
855
 
    def summarize(self, verbose=None):
856
 
        """
857
 
        verbose=None -> summarize results, return (#failures, #tests).
858
 
 
859
 
        Print summary of test results to stdout.
860
 
        Optional arg 'verbose' controls how wordy this is.  By
861
 
        default, use the verbose setting established by the
862
 
        constructor.
863
 
        """
864
 
 
865
 
        if verbose is None:
866
 
            verbose = self.verbose
867
 
        notests = []
868
 
        passed = []
869
 
        failed = []
870
 
        totalt = totalf = 0
871
 
        for x in self.name2ft.items():
872
 
            name, (f, t) = x
873
 
            assert f <= t
874
 
            totalt = totalt + t
875
 
            totalf = totalf + f
876
 
            if t == 0:
877
 
                notests.append(name)
878
 
            elif f == 0:
879
 
                passed.append( (name, t) )
880
 
            else:
881
 
                failed.append(x)
882
 
        if verbose:
883
 
            if notests:
884
 
                print len(notests), "items had no tests:"
885
 
                notests.sort()
886
 
                for thing in notests:
887
 
                    print "   ", thing
888
 
            if passed:
889
 
                print len(passed), "items passed all tests:"
890
 
                passed.sort()
891
 
                for thing, count in passed:
892
 
                    print " %3d tests in %s" % (count, thing)
893
 
        if failed:
894
 
            print len(failed), "items had failures:"
895
 
            failed.sort()
896
 
            for thing, (f, t) in failed:
897
 
                print " %3d of %3d in %s" % (f, t, thing)
898
 
        if verbose:
899
 
            print totalt, "tests in", len(self.name2ft), "items."
900
 
            print totalt - totalf, "passed and", totalf, "failed."
901
 
        if totalf:
902
 
            print "***Test Failed***", totalf, "failures."
903
 
        elif verbose:
904
 
            print "Test passed."
905
 
        return totalf, totalt
906
 
 
907
 
    def merge(self, other):
908
 
        """
909
 
        other -> merge in test results from the other Tester instance.
910
 
 
911
 
        If self and other both have a test result for something
912
 
        with the same name, the (#failures, #tests) results are
913
 
        summed, and a warning is printed to stdout.
914
 
 
915
 
        >>> from doctest import Tester
916
 
        >>> t1 = Tester(globs={}, verbose=0)
917
 
        >>> t1.runstring('''
918
 
        ... >>> x = 12
919
 
        ... >>> print x
920
 
        ... 12
921
 
        ... ''', "t1example")
922
 
        (0, 2)
923
 
        >>>
924
 
        >>> t2 = Tester(globs={}, verbose=0)
925
 
        >>> t2.runstring('''
926
 
        ... >>> x = 13
927
 
        ... >>> print x
928
 
        ... 13
929
 
        ... ''', "t2example")
930
 
        (0, 2)
931
 
        >>> common = ">>> assert 1 + 2 == 3\\n"
932
 
        >>> t1.runstring(common, "common")
933
 
        (0, 1)
934
 
        >>> t2.runstring(common, "common")
935
 
        (0, 1)
936
 
        >>> t1.merge(t2)
937
 
        *** Tester.merge: 'common' in both testers; summing outcomes.
938
 
        >>> t1.summarize(1)
939
 
        3 items passed all tests:
940
 
           2 tests in common
941
 
           2 tests in t1example
942
 
           2 tests in t2example
943
 
        6 tests in 3 items.
944
 
        6 passed and 0 failed.
945
 
        Test passed.
946
 
        (0, 6)
947
 
        >>>
948
 
        """
949
 
 
950
 
        d = self.name2ft
951
 
        for name, (f, t) in other.name2ft.items():
952
 
            if d.has_key(name):
953
 
                print "*** Tester.merge: '" + name + "' in both" \
954
 
                    " testers; summing outcomes."
955
 
                f2, t2 = d[name]
956
 
                f = f + f2
957
 
                t = t + t2
958
 
            d[name] = f, t
959
 
 
960
 
    def __record_outcome(self, name, f, t):
961
 
        if self.name2ft.has_key(name):
962
 
            print "*** Warning: '" + name + "' was tested before;", \
963
 
                "summing outcomes."
964
 
            f2, t2 = self.name2ft[name]
965
 
            f = f + f2
966
 
            t = t + t2
967
 
        self.name2ft[name] = f, t
968
 
 
969
 
    def __runone(self, target, name):
970
 
        if "." in name:
971
 
            i = _string_rindex(name, ".")
972
 
            prefix, base = name[:i], name[i+1:]
973
 
        else:
974
 
            prefix, base = "", base
975
 
        if self.isprivate(prefix, base):
976
 
            return 0, 0
977
 
        return self.rundoc(target, name)
978
 
 
979
 
master = None
980
 
 
981
 
def testmod(m, name=None, globs=None, verbose=None, isprivate=None,
982
 
               report=1):
983
 
    """m, name=None, globs=None, verbose=None, isprivate=None, report=1
984
 
 
985
 
    Test examples in docstrings in functions and classes reachable from
986
 
    module m, starting with m.__doc__.  Private names are skipped.
987
 
 
988
 
    Also test examples reachable from dict m.__test__ if it exists and is
989
 
    not None.  m.__dict__ maps names to functions, classes and strings;
990
 
    function and class docstrings are tested even if the name is private;
991
 
    strings are tested directly, as if they were docstrings.
992
 
 
993
 
    Return (#failures, #tests).
994
 
 
995
 
    See doctest.__doc__ for an overview.
996
 
 
997
 
    Optional keyword arg "name" gives the name of the module; by default
998
 
    use m.__name__.
999
 
 
1000
 
    Optional keyword arg "globs" gives a dict to be used as the globals
1001
 
    when executing examples; by default, use m.__dict__.  A copy of this
1002
 
    dict is actually used for each docstring, so that each docstring's
1003
 
    examples start with a clean slate.
1004
 
 
1005
 
    Optional keyword arg "verbose" prints lots of stuff if true, prints
1006
 
    only failures if false; by default, it's true iff "-v" is in sys.argv.
1007
 
 
1008
 
    Optional keyword arg "isprivate" specifies a function used to
1009
 
    determine whether a name is private.  The default function is
1010
 
    doctest.is_private; see its docs for details.
1011
 
 
1012
 
    Optional keyword arg "report" prints a summary at the end when true,
1013
 
    else prints nothing at the end.  In verbose mode, the summary is
1014
 
    detailed, else very brief (in fact, empty if all tests passed).
1015
 
 
1016
 
    Advanced tomfoolery:  testmod runs methods of a local instance of
1017
 
    class doctest.Tester, then merges the results into (or creates)
1018
 
    global Tester instance doctest.master.  Methods of doctest.master
1019
 
    can be called directly too, if you want to do something unusual.
1020
 
    Passing report=0 to testmod is especially useful then, to delay
1021
 
    displaying a summary.  Invoke doctest.master.summarize(verbose)
1022
 
    when you're done fiddling.
1023
 
    """
1024
 
 
1025
 
    global master
1026
 
 
1027
 
    if type(m) is not _ModuleType:
1028
 
        raise TypeError("testmod: module required; " + `m`)
1029
 
    if name is None:
1030
 
        name = m.__name__
1031
 
    tester = Tester(m, globs=globs, verbose=verbose, isprivate=isprivate)
1032
 
    failures, tries = tester.rundoc(m, name)
1033
 
    f, t = tester.rundict(m.__dict__, name)
1034
 
    failures = failures + f
1035
 
    tries = tries + t
1036
 
    if hasattr(m, "__test__"):
1037
 
        testdict = m.__test__
1038
 
        if testdict:
1039
 
            if not hasattr(testdict, "items"):
1040
 
                raise TypeError("testmod: module.__test__ must support "
1041
 
                                ".items(); " + `testdict`)
1042
 
            f, t = tester.run__test__(testdict, name + ".__test__")
1043
 
            failures = failures + f
1044
 
            tries = tries + t
1045
 
    if report:
1046
 
        tester.summarize()
1047
 
    if master is None:
1048
 
        master = tester
1049
 
    else:
1050
 
        master.merge(tester)
1051
 
    return failures, tries
1052
 
 
1053
 
class _TestClass:
1054
 
    """
1055
 
    A pointless class, for sanity-checking of docstring testing.
1056
 
 
1057
 
    Methods:
1058
 
        square()
1059
 
        get()
1060
 
 
1061
 
    >>> _TestClass(13).get() + _TestClass(-12).get()
1062
 
    1
1063
 
    >>> hex(_TestClass(13).square().get())
1064
 
    '0xa9'
1065
 
    """
1066
 
 
1067
 
    def __init__(self, val):
1068
 
        """val -> _TestClass object with associated value val.
1069
 
 
1070
 
        >>> t = _TestClass(123)
1071
 
        >>> print t.get()
1072
 
        123
1073
 
        """
1074
 
 
1075
 
        self.val = val
1076
 
 
1077
 
    def square(self):
1078
 
        """square() -> square TestClass's associated value
1079
 
 
1080
 
        >>> _TestClass(13).square().get()
1081
 
        169
1082
 
        """
1083
 
 
1084
 
        self.val = self.val ** 2
1085
 
        return self
1086
 
 
1087
 
    def get(self):
1088
 
        """get() -> return TestClass's associated value.
1089
 
 
1090
 
        >>> x = _TestClass(-42)
1091
 
        >>> print x.get()
1092
 
        -42
1093
 
        """
1094
 
 
1095
 
        return self.val
1096
 
 
1097
 
__test__ = {"_TestClass": _TestClass,
1098
 
            "string": r"""
1099
 
                      Example of a string object, searched as-is.
1100
 
                      >>> x = 1; y = 2
1101
 
                      >>> x + y, x * y
1102
 
                      (3, 2)
1103
 
                      """
1104
 
           }
1105
 
 
1106
 
def _test():
1107
 
    import doctest
1108
 
    return doctest.testmod(doctest)
1109
 
 
1110
 
if __name__ == "__main__":
1111
 
    _test()