~launchpad/zope.testing/3.9.4-p4

« back to all changes in this revision

Viewing changes to src/zope/testing/doctest/__init__.py

  • Committer: Maris Fogels
  • Date: 2010-06-04 14:58:44 UTC
  • Revision ID: maris.fogels@canonical.com-20100604145844-mb48c1ig9gty2kao
Initial import of zope.testing's 3.9.4 SVN tag

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Module doctest.
 
2
# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
 
3
# Major enhancements and refactoring by:
 
4
#     Jim Fulton
 
5
#     Edward Loper
 
6
 
 
7
# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
 
8
 
 
9
r"""Module doctest -- a framework for running examples in docstrings.
 
10
 
 
11
In simplest use, end each module M to be tested with:
 
12
 
 
13
def _test():
 
14
    import doctest
 
15
    doctest.testmod()
 
16
 
 
17
if __name__ == "__main__":
 
18
    _test()
 
19
 
 
20
Then running the module as a script will cause the examples in the
 
21
docstrings to get executed and verified:
 
22
 
 
23
python M.py
 
24
 
 
25
This won't display anything unless an example fails, in which case the
 
26
failing 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
 
28
line of output is "Test failed.".
 
29
 
 
30
Run it with the -v switch instead:
 
31
 
 
32
python M.py -v
 
33
 
 
34
and a detailed report of all examples tried is printed to stdout, along
 
35
with assorted summaries at the end.
 
36
 
 
37
You can force verbose mode by passing "verbose=True" to testmod, or prohibit
 
38
it by passing "verbose=False".  In either of those cases, sys.argv is not
 
39
examined by testmod.
 
40
 
 
41
There are a variety of other ways to run doctests, including integration
 
42
with the unittest framework, and support for running non-Python text
 
43
files containing doctests.  There are also many ways to override parts
 
44
of doctest's default behaviors.  See the Library Reference Manual for
 
45
details.
 
46
"""
 
47
 
 
48
__docformat__ = 'reStructuredText en'
 
49
 
 
50
__all__ = [
 
51
    # 0, Option Flags
 
52
    'register_optionflag',
 
53
    'DONT_ACCEPT_TRUE_FOR_1',
 
54
    'DONT_ACCEPT_BLANKLINE',
 
55
    'NORMALIZE_WHITESPACE',
 
56
    'ELLIPSIS',
 
57
    'IGNORE_EXCEPTION_DETAIL',
 
58
    'COMPARISON_FLAGS',
 
59
    'REPORT_UDIFF',
 
60
    'REPORT_CDIFF',
 
61
    'REPORT_NDIFF',
 
62
    'REPORT_ONLY_FIRST_FAILURE',
 
63
    'REPORTING_FLAGS',
 
64
    # 1. Utility Functions
 
65
    'is_private',
 
66
    # 2. Example & DocTest
 
67
    'Example',
 
68
    'DocTest',
 
69
    # 3. Doctest Parser
 
70
    'DocTestParser',
 
71
    # 4. Doctest Finder
 
72
    'DocTestFinder',
 
73
    # 5. Doctest Runner
 
74
    'DocTestRunner',
 
75
    'OutputChecker',
 
76
    'DocTestFailure',
 
77
    'UnexpectedException',
 
78
    'DebugRunner',
 
79
    # 6. Test Functions
 
80
    'testmod',
 
81
    'testfile',
 
82
    'run_docstring_examples',
 
83
    # 7. Tester
 
84
    'Tester',
 
85
    # 8. Unittest Support
 
86
    'DocTestSuite',
 
87
    'DocFileSuite',
 
88
    'set_unittest_reportflags',
 
89
    # 9. Debugging Support
 
90
    'script_from_examples',
 
91
    'testsource',
 
92
    'debug_src',
 
93
    'debug',
 
94
]
 
95
 
 
96
import __future__
 
97
 
 
98
import doctest
 
99
import sys, traceback, inspect, linecache, os, re
 
100
import unittest, difflib, pdb, tempfile
 
101
import warnings
 
102
from doctest import DocTestFailure, UnexpectedException
 
103
from StringIO import StringIO
 
104
from zope.testing.exceptions import DocTestFailureException
 
105
 
 
106
# Don't whine about the deprecated is_private function in this
 
107
# module's tests.
 
108
warnings.filterwarnings("ignore", "is_private", DeprecationWarning,
 
109
                        __name__, 0)
 
110
 
 
111
# Tell people to use the builtin module instead.
 
112
warnings.warn('zope.testing.doctest is deprecated in favour of '
 
113
              'the Python standard library doctest module', DeprecationWarning,
 
114
               stacklevel=2)
 
115
 
 
116
class UnusedFootnoteWarning(Warning):
 
117
    """Warn about a footnote that is defined, but never referenced."""
 
118
 
 
119
real_pdb_set_trace = pdb.set_trace
 
120
 
 
121
# There are 4 basic classes:
 
122
#  - Example: a <source, want> pair, plus an intra-docstring line number.
 
123
#  - DocTest: a collection of examples, parsed from a docstring, plus
 
124
#    info about where the docstring came from (name, filename, lineno).
 
125
#  - DocTestFinder: extracts DocTests from a given object's docstring and
 
126
#    its contained objects' docstrings.
 
127
#  - DocTestRunner: runs DocTest cases, and accumulates statistics.
 
128
#
 
129
# So the basic picture is:
 
130
#
 
131
#                             list of:
 
132
# +------+                   +---------+                   +-------+
 
133
# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
 
134
# +------+                   +---------+                   +-------+
 
135
#                            | Example |
 
136
#                            |   ...   |
 
137
#                            | Example |
 
138
#                            +---------+
 
139
 
 
140
# Option constants.
 
141
 
 
142
from doctest import register_optionflag, \
 
143
    OPTIONFLAGS_BY_NAME, \
 
144
    DONT_ACCEPT_TRUE_FOR_1, \
 
145
    DONT_ACCEPT_BLANKLINE, \
 
146
    NORMALIZE_WHITESPACE, \
 
147
    ELLIPSIS, \
 
148
    IGNORE_EXCEPTION_DETAIL, \
 
149
    COMPARISON_FLAGS, \
 
150
    REPORT_UDIFF, \
 
151
    REPORT_CDIFF, \
 
152
    REPORT_NDIFF, \
 
153
    REPORT_ONLY_FIRST_FAILURE, \
 
154
    REPORTING_FLAGS
 
155
 
 
156
INTERPRET_FOOTNOTES = register_optionflag('INTERPRET_FOOTNOTES')
 
157
 
 
158
# Special string markers for use in `want` strings:
 
159
BLANKLINE_MARKER = '<BLANKLINE>'
 
160
ELLIPSIS_MARKER = '...'
 
161
 
 
162
######################################################################
 
163
## Table of Contents
 
164
######################################################################
 
165
#  1. Utility Functions
 
166
#  2. Example & DocTest -- store test cases
 
167
#  3. DocTest Parser -- extracts examples from strings
 
168
#  4. DocTest Finder -- extracts test cases from objects
 
169
#  5. DocTest Runner -- runs test cases
 
170
#  6. Test Functions -- convenient wrappers for testing
 
171
#  7. Tester Class -- for backwards compatibility
 
172
#  8. Unittest Support
 
173
#  9. Debugging Support
 
174
# 10. Example Usage
 
175
 
 
176
######################################################################
 
177
## 1. Utility Functions
 
178
######################################################################
 
179
 
 
180
def is_private(prefix, base):
 
181
    """prefix, base -> true iff name prefix + "." + base is "private".
 
182
 
 
183
    Prefix may be an empty string, and base does not contain a period.
 
184
    Prefix is ignored (although functions you write conforming to this
 
185
    protocol may make use of it).
 
186
    Return true iff base begins with an (at least one) underscore, but
 
187
    does not both begin and end with (at least) two underscores.
 
188
 
 
189
    >>> is_private("a.b", "my_func")
 
190
    False
 
191
    >>> is_private("____", "_my_func")
 
192
    True
 
193
    >>> is_private("someclass", "__init__")
 
194
    False
 
195
    >>> is_private("sometypo", "__init_")
 
196
    True
 
197
    >>> is_private("x.y.z", "_")
 
198
    True
 
199
    >>> is_private("_x.y.z", "__")
 
200
    False
 
201
    >>> is_private("", "")  # senseless but consistent
 
202
    False
 
203
    """
 
204
    warnings.warn("is_private is deprecated; it wasn't useful; "
 
205
                  "examine DocTestFinder.find() lists instead",
 
206
                  DeprecationWarning, stacklevel=2)
 
207
    return base[:1] == "_" and not base[:2] == "__" == base[-2:]
 
208
 
 
209
def _extract_future_flags(globs):
 
210
    """
 
211
    Return the compiler-flags associated with the future features that
 
212
    have been imported into the given namespace (globs).
 
213
    """
 
214
    flags = 0
 
215
    for fname in __future__.all_feature_names:
 
216
        feature = globs.get(fname, None)
 
217
        if feature is getattr(__future__, fname):
 
218
            flags |= feature.compiler_flag
 
219
    return flags
 
220
 
 
221
def _normalize_module(module, depth=2):
 
222
    """
 
223
    Return the module specified by `module`.  In particular:
 
224
      - If `module` is a module, then return module.
 
225
      - If `module` is a string, then import and return the
 
226
        module with that name.
 
227
      - If `module` is None, then return the calling module.
 
228
        The calling module is assumed to be the module of
 
229
        the stack frame at the given depth in the call stack.
 
230
    """
 
231
    if inspect.ismodule(module):
 
232
        return module
 
233
    elif isinstance(module, (str, unicode)):
 
234
        return __import__(module, globals(), locals(), ["*"])
 
235
    elif module is None:
 
236
        return sys.modules[sys._getframe(depth).f_globals['__name__']]
 
237
    else:
 
238
        raise TypeError("Expected a module, string, or None")
 
239
 
 
240
def _indent(s, indent=4):
 
241
    """
 
242
    Add the given number of space characters to the beginning every
 
243
    non-blank line in `s`, and return the result.
 
244
    """
 
245
    # This regexp matches the start of non-blank lines:
 
246
    return re.sub('(?m)^(?!$)', indent*' ', s)
 
247
 
 
248
def _exception_traceback(exc_info):
 
249
    """
 
250
    Return a string containing a traceback message for the given
 
251
    exc_info tuple (as returned by sys.exc_info()).
 
252
    """
 
253
    # Get a traceback message.
 
254
    excout = StringIO()
 
255
    exc_type, exc_val, exc_tb = exc_info
 
256
    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
 
257
    return excout.getvalue()
 
258
 
 
259
# Override some StringIO methods.
 
260
class _SpoofOut(StringIO):
 
261
    def getvalue(self):
 
262
        result = StringIO.getvalue(self)
 
263
        # If anything at all was written, make sure there's a trailing
 
264
        # newline.  There's no way for the expected output to indicate
 
265
        # that a trailing newline is missing.
 
266
        if result and not result.endswith("\n"):
 
267
            result += "\n"
 
268
        # Prevent softspace from screwing up the next test case, in
 
269
        # case they used print with a trailing comma in an example.
 
270
        if hasattr(self, "softspace"):
 
271
            del self.softspace
 
272
        return result
 
273
 
 
274
    def truncate(self,   size=None):
 
275
        StringIO.truncate(self, size)
 
276
        if hasattr(self, "softspace"):
 
277
            del self.softspace
 
278
 
 
279
    def write(self, value):
 
280
        if isinstance(value, unicode):
 
281
            value = value.encode('utf8')
 
282
        StringIO.write(self, value)
 
283
 
 
284
# Worst-case linear-time ellipsis matching.
 
285
def _ellipsis_match(want, got):
 
286
    """
 
287
    Essentially the only subtle case:
 
288
    >>> _ellipsis_match('aa...aa', 'aaa')
 
289
    False
 
290
    """
 
291
    if ELLIPSIS_MARKER not in want:
 
292
        return want == got
 
293
 
 
294
    # Find "the real" strings.
 
295
    ws = want.split(ELLIPSIS_MARKER)
 
296
    assert len(ws) >= 2
 
297
 
 
298
    # Deal with exact matches possibly needed at one or both ends.
 
299
    startpos, endpos = 0, len(got)
 
300
    w = ws[0]
 
301
    if w:   # starts with exact match
 
302
        if got.startswith(w):
 
303
            startpos = len(w)
 
304
            del ws[0]
 
305
        else:
 
306
            return False
 
307
    w = ws[-1]
 
308
    if w:   # ends with exact match
 
309
        if got.endswith(w):
 
310
            endpos -= len(w)
 
311
            del ws[-1]
 
312
        else:
 
313
            return False
 
314
 
 
315
    if startpos > endpos:
 
316
        # Exact end matches required more characters than we have, as in
 
317
        # _ellipsis_match('aa...aa', 'aaa')
 
318
        return False
 
319
 
 
320
    # For the rest, we only need to find the leftmost non-overlapping
 
321
    # match for each piece.  If there's no overall match that way alone,
 
322
    # there's no overall match period.
 
323
    for w in ws:
 
324
        # w may be '' at times, if there are consecutive ellipses, or
 
325
        # due to an ellipsis at the start or end of `want`.  That's OK.
 
326
        # Search for an empty string succeeds, and doesn't change startpos.
 
327
        startpos = got.find(w, startpos, endpos)
 
328
        if startpos < 0:
 
329
            return False
 
330
        startpos += len(w)
 
331
 
 
332
    return True
 
333
 
 
334
def _comment_line(line):
 
335
    "Return a commented form of the given line"
 
336
    line = line.rstrip()
 
337
    if line:
 
338
        return '# '+line
 
339
    else:
 
340
        return '#'
 
341
 
 
342
class _OutputRedirectingPdb(pdb.Pdb):
 
343
    """
 
344
    A specialized version of the python debugger that redirects stdout
 
345
    to a given stream when interacting with the user.  Stdout is *not*
 
346
    redirected when traced code is executed.
 
347
    """
 
348
    def __init__(self, out):
 
349
        self.__out = out
 
350
        self.__debugger_used = False
 
351
        try:
 
352
            pdb.Pdb.__init__(self, stdin=sys.stdin, stdout=out)
 
353
        except TypeError:
 
354
            pdb.Pdb.__init__(self)
 
355
        # enable readline
 
356
        self.use_rawinput = 1
 
357
 
 
358
    def set_trace(self):
 
359
        self.__debugger_used = True
 
360
        pdb.Pdb.set_trace(self)
 
361
 
 
362
    def set_continue(self):
 
363
        # Calling set_continue unconditionally would break unit test coverage
 
364
        # reporting, as Bdb.set_continue calls sys.settrace(None).
 
365
        if self.__debugger_used:
 
366
            pdb.Pdb.set_continue(self)
 
367
 
 
368
    def trace_dispatch(self, *args):
 
369
        # Redirect stdout to the given stream.
 
370
        save_stdout = sys.stdout
 
371
        sys.stdout = self.__out
 
372
        # Call Pdb's trace dispatch method.
 
373
        result = pdb.Pdb.trace_dispatch(self, *args)
 
374
        # Restore stdout.
 
375
        sys.stdout = save_stdout
 
376
        return result
 
377
 
 
378
# [XX] Normalize with respect to os.path.pardir?
 
379
def _module_relative_path(module, path):
 
380
    if not inspect.ismodule(module):
 
381
        raise TypeError('Expected a module: %r' % module)
 
382
    if path.startswith('/'):
 
383
        raise ValueError('Module-relative files may not have absolute paths')
 
384
 
 
385
    # Find the base directory for the path.
 
386
    if hasattr(module, '__file__'):
 
387
        # A normal module/package
 
388
        basedir = os.path.split(module.__file__)[0]
 
389
    elif module.__name__ == '__main__':
 
390
        # An interactive session.
 
391
        if len(sys.argv)>0 and sys.argv[0] != '':
 
392
            basedir = os.path.split(sys.argv[0])[0]
 
393
        else:
 
394
            basedir = os.curdir
 
395
    else:
 
396
        # A module w/o __file__ (this includes builtins)
 
397
        raise ValueError("Can't resolve paths relative to the module " +
 
398
                         module + " (it has no __file__)")
 
399
 
 
400
    # Combine the base directory and the path.
 
401
    return os.path.join(basedir, *(path.split('/')))
 
402
 
 
403
######################################################################
 
404
## 2. Example & DocTest
 
405
######################################################################
 
406
## - An "example" is a <source, want> pair, where "source" is a
 
407
##   fragment of source code, and "want" is the expected output for
 
408
##   "source."  The Example class also includes information about
 
409
##   where the example was extracted from.
 
410
##
 
411
## - A "doctest" is a collection of examples, typically extracted from
 
412
##   a string (such as an object's docstring).  The DocTest class also
 
413
##   includes information about where the string was extracted from.
 
414
 
 
415
class Example:
 
416
    """
 
417
    A single doctest example, consisting of source code and expected
 
418
    output.  `Example` defines the following attributes:
 
419
 
 
420
      - source: A single Python statement, always ending with a newline.
 
421
        The constructor adds a newline if needed.
 
422
 
 
423
      - want: The expected output from running the source code (either
 
424
        from stdout, or a traceback in case of exception).  `want` ends
 
425
        with a newline unless it's empty, in which case it's an empty
 
426
        string.  The constructor adds a newline if needed.
 
427
 
 
428
      - exc_msg: The exception message generated by the example, if
 
429
        the example is expected to generate an exception; or `None` if
 
430
        it is not expected to generate an exception.  This exception
 
431
        message is compared against the return value of
 
432
        `traceback.format_exception_only()`.  `exc_msg` ends with a
 
433
        newline unless it's `None`.  The constructor adds a newline
 
434
        if needed.
 
435
 
 
436
      - lineno: The line number within the DocTest string containing
 
437
        this Example where the Example begins.  This line number is
 
438
        zero-based, with respect to the beginning of the DocTest.
 
439
 
 
440
      - indent: The example's indentation in the DocTest string.
 
441
        I.e., the number of space characters that preceed the
 
442
        example's first prompt.
 
443
 
 
444
      - options: A dictionary mapping from option flags to True or
 
445
        False, which is used to override default options for this
 
446
        example.  Any option flags not contained in this dictionary
 
447
        are left at their default value (as specified by the
 
448
        DocTestRunner's optionflags).  By default, no options are set.
 
449
    """
 
450
    def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
 
451
                 options=None):
 
452
        # Normalize inputs.
 
453
        if not source.endswith('\n'):
 
454
            source += '\n'
 
455
        if want and not want.endswith('\n'):
 
456
            want += '\n'
 
457
        if exc_msg is not None and not exc_msg.endswith('\n'):
 
458
            exc_msg += '\n'
 
459
        # Store properties.
 
460
        self.source = source
 
461
        self.want = want
 
462
        self.lineno = lineno
 
463
        self.indent = indent
 
464
        if options is None: options = {}
 
465
        self.options = options
 
466
        self.exc_msg = exc_msg
 
467
 
 
468
class DocTest:
 
469
    """
 
470
    A collection of doctest examples that should be run in a single
 
471
    namespace.  Each `DocTest` defines the following attributes:
 
472
 
 
473
      - examples: the list of examples.
 
474
 
 
475
      - globs: The namespace (aka globals) that the examples should
 
476
        be run in.
 
477
 
 
478
      - name: A name identifying the DocTest (typically, the name of
 
479
        the object whose docstring this DocTest was extracted from).
 
480
 
 
481
      - filename: The name of the file that this DocTest was extracted
 
482
        from, or `None` if the filename is unknown.
 
483
 
 
484
      - lineno: The line number within filename where this DocTest
 
485
        begins, or `None` if the line number is unavailable.  This
 
486
        line number is zero-based, with respect to the beginning of
 
487
        the file.
 
488
 
 
489
      - docstring: The string that the examples were extracted from,
 
490
        or `None` if the string is unavailable.
 
491
    """
 
492
    def __init__(self, examples, globs, name, filename, lineno, docstring):
 
493
        """
 
494
        Create a new DocTest containing the given examples.  The
 
495
        DocTest's globals are initialized with a copy of `globs`.
 
496
        """
 
497
        assert not isinstance(examples, basestring), \
 
498
               "DocTest no longer accepts str; use DocTestParser instead"
 
499
        self.examples = examples
 
500
        self.docstring = docstring
 
501
        self.globs = globs.copy()
 
502
        self.name = name
 
503
        self.filename = filename
 
504
        self.lineno = lineno
 
505
 
 
506
    def __repr__(self):
 
507
        if len(self.examples) == 0:
 
508
            examples = 'no examples'
 
509
        elif len(self.examples) == 1:
 
510
            examples = '1 example'
 
511
        else:
 
512
            examples = '%d examples' % len(self.examples)
 
513
        return ('<DocTest %s from %s:%s (%s)>' %
 
514
                (self.name, self.filename, self.lineno, examples))
 
515
 
 
516
 
 
517
    # This lets us sort tests by name:
 
518
    def __cmp__(self, other):
 
519
        if not isinstance(other, DocTest):
 
520
            return -1
 
521
        return cmp((self.name, self.filename, self.lineno, id(self)),
 
522
                   (other.name, other.filename, other.lineno, id(other)))
 
523
 
 
524
######################################################################
 
525
## 3. DocTestParser
 
526
######################################################################
 
527
 
 
528
class DocTestParser:
 
529
    """
 
530
    A class used to parse strings containing doctest examples.
 
531
    """
 
532
    # This regular expression is used to find doctest examples in a
 
533
    # string.  It defines three groups: `source` is the source code
 
534
    # (including leading indentation and prompts); `indent` is the
 
535
    # indentation of the first (PS1) line of the source code; and
 
536
    # `want` is the expected output (including leading indentation).
 
537
    _EXAMPLE_RE = re.compile(r'''
 
538
        # Source consists of a PS1 line followed by zero or more PS2 lines.
 
539
        (?P<source>
 
540
            (?:^(?P<indent> [ ]*) >>>    .*)    # PS1 line
 
541
            (?:\n           [ ]*  \.\.\. .*)*)  # PS2 lines
 
542
        \n?
 
543
        # Want consists of any non-blank lines that do not start with PS1.
 
544
        (?P<want> (?:(?![ ]*$)    # Not a blank line
 
545
                     (?![ ]*>>>)  # Not a line starting with PS1
 
546
                     .*$\n?       # But any other line
 
547
                  )*)
 
548
        ''', re.MULTILINE | re.VERBOSE)
 
549
 
 
550
    # A regular expression for handling `want` strings that contain
 
551
    # expected exceptions.  It divides `want` into three pieces:
 
552
    #    - the traceback header line (`hdr`)
 
553
    #    - the traceback stack (`stack`)
 
554
    #    - the exception message (`msg`), as generated by
 
555
    #      traceback.format_exception_only()
 
556
    # `msg` may have multiple lines.  We assume/require that the
 
557
    # exception message is the first non-indented line starting with a word
 
558
    # character following the traceback header line.
 
559
    _EXCEPTION_RE = re.compile(r"""
 
560
        # Grab the traceback header.  Different versions of Python have
 
561
        # said different things on the first traceback line.
 
562
        ^(?P<hdr> Traceback\ \(
 
563
            (?: most\ recent\ call\ last
 
564
            |   innermost\ last
 
565
            ) \) :
 
566
        )
 
567
        \s* $                # toss trailing whitespace on the header.
 
568
        (?P<stack> .*?)      # don't blink: absorb stuff until...
 
569
        ^ (?P<msg> \w+ .*)   #     a line *starts* with alphanum.
 
570
        """, re.VERBOSE | re.MULTILINE | re.DOTALL)
 
571
 
 
572
    # A callable returning a true value iff its argument is a blank line
 
573
    # or contains a single comment.
 
574
    _IS_BLANK_OR_COMMENT = re.compile(r'^[ ]*(#.*)?$').match
 
575
 
 
576
    # Find footnote references.
 
577
    _FOOTNOTE_REFERENCE_RE = re.compile(r'\[([^\]]+)]_')
 
578
 
 
579
    # Find footnote definitions.
 
580
    _FOOTNOTE_DEFINITION_RE = re.compile(
 
581
        r'^\.\.\s*\[\s*([^\]]+)\s*\].*$', re.MULTILINE)
 
582
 
 
583
    # End of footnote regex.   Just looks for any unindented line.
 
584
    _FOOTNOTE_END_RE = re.compile(r'^\S+', re.MULTILINE)
 
585
 
 
586
    def parse(self, string, name='<string>', optionflags=0):
 
587
        """
 
588
        Divide the given string into examples and intervening text,
 
589
        and return them as a list of alternating Examples and strings.
 
590
        Line numbers for the Examples are 0-based.  The optional
 
591
        argument `name` is a name identifying this string, and is only
 
592
        used for error messages.
 
593
        """
 
594
        string = string.expandtabs()
 
595
        # If all lines begin with the same indentation, then strip it.
 
596
        min_indent = self._min_indent(string)
 
597
        if min_indent > 0:
 
598
            string = '\n'.join([l[min_indent:] for l in string.split('\n')])
 
599
 
 
600
        output = []
 
601
        charno, lineno = 0, 0
 
602
        # Find all doctest examples in the string:
 
603
        for m in self._EXAMPLE_RE.finditer(string):
 
604
            # Add the pre-example text to `output`.
 
605
            output.append(string[charno:m.start()])
 
606
            # Update lineno (lines before this example)
 
607
            lineno += string.count('\n', charno, m.start())
 
608
            # Extract info from the regexp match.
 
609
            (source, options, want, exc_msg) = \
 
610
                     self._parse_example(m, name, lineno)
 
611
            # Create an Example, and add it to the list.
 
612
            if not self._IS_BLANK_OR_COMMENT(source):
 
613
                output.append( Example(source, want, exc_msg,
 
614
                                    lineno=lineno,
 
615
                                    indent=min_indent+len(m.group('indent')),
 
616
                                    options=options) )
 
617
            # Update lineno (lines inside this example)
 
618
            lineno += string.count('\n', m.start(), m.end())
 
619
            # Update charno.
 
620
            charno = m.end()
 
621
        # Add any remaining post-example text to `output`.
 
622
        output.append(string[charno:])
 
623
 
 
624
        if optionflags & INTERPRET_FOOTNOTES:
 
625
            footnotes = {}
 
626
            in_footnote = False
 
627
            # collect all the footnotes
 
628
            for x in output:
 
629
                if in_footnote:
 
630
                    footnote.append(x)
 
631
                    # we're collecting prose and examples for a footnote
 
632
                    if isinstance(x, Example):
 
633
                        x._footnote_name = name
 
634
                    elif self._FOOTNOTE_END_RE.search(x):
 
635
                        # this looks like prose that ends a footnote
 
636
                        in_footnote = False
 
637
                        footnotes[name] = footnote
 
638
                        del name
 
639
                        del footnote
 
640
 
 
641
                if not in_footnote:
 
642
                    if not isinstance(x, Example):
 
643
                        matches = list(
 
644
                            self._FOOTNOTE_DEFINITION_RE.finditer(x))
 
645
 
 
646
                        if matches:
 
647
                            # all but the last one don't have any code
 
648
                            # note: we intentionally reuse the "leaked" value
 
649
                            # of match below
 
650
                            for match in matches:
 
651
                                footnotes[match.group(1)] = []
 
652
 
 
653
                            in_footnote = True
 
654
                            name = match.group(1)
 
655
                            footnote = []
 
656
 
 
657
            # if we were still collecting a footnote when the loop ended,
 
658
            # stash it away so it's not lost
 
659
            if in_footnote:
 
660
                footnotes[name] = footnote
 
661
 
 
662
            # inject each footnote into the point(s) at which it is referenced
 
663
            new_output = []
 
664
            defined_footnotes = []
 
665
            used_footnotes = []
 
666
            for x in output:
 
667
                if isinstance(x, Example):
 
668
                    # we don't want to execute footnotes where they're defined
 
669
                    if hasattr(x, '_footnote_name'):
 
670
                        defined_footnotes.append(x._footnote_name)
 
671
                        continue
 
672
                else:
 
673
                    m = None
 
674
                    for m in self._FOOTNOTE_REFERENCE_RE.finditer(x):
 
675
                        name = m.group(1)
 
676
                        if name not in footnotes:
 
677
                            raise KeyError(
 
678
                                'A footnote was referred to, but never'
 
679
                                ' defined: %r' % name)
 
680
 
 
681
                        new_output.append(x)
 
682
                        new_output.extend(footnotes[name])
 
683
                        used_footnotes.append(name)
 
684
                    if m is not None:
 
685
                        continue
 
686
 
 
687
                new_output.append(x)
 
688
            output = new_output
 
689
 
 
690
            # make sure that all of the footnotes found were actually used
 
691
            unused_footnotes = set(defined_footnotes) - set(used_footnotes)
 
692
            for x in unused_footnotes:
 
693
                warnings.warn('a footnote was defined, but never used: %r' % x,
 
694
                              UnusedFootnoteWarning)
 
695
 
 
696
        return output
 
697
 
 
698
    def get_doctest(self, string, globs, name, filename, lineno,
 
699
                    optionflags=0):
 
700
        """
 
701
        Extract all doctest examples from the given string, and
 
702
        collect them into a `DocTest` object.
 
703
 
 
704
        `globs`, `name`, `filename`, and `lineno` are attributes for
 
705
        the new `DocTest` object.  See the documentation for `DocTest`
 
706
        for more information.
 
707
        """
 
708
        return DocTest(self.get_examples(string, name, optionflags), globs,
 
709
                       name, filename, lineno, string)
 
710
 
 
711
    def get_examples(self, string, name='<string>', optionflags=0):
 
712
        """
 
713
        Extract all doctest examples from the given string, and return
 
714
        them as a list of `Example` objects.  Line numbers are
 
715
        0-based, because it's most common in doctests that nothing
 
716
        interesting appears on the same line as opening triple-quote,
 
717
        and so the first interesting line is called \"line 1\" then.
 
718
 
 
719
        The optional argument `name` is a name identifying this
 
720
        string, and is only used for error messages.
 
721
        """
 
722
        return [x for x in self.parse(string, name, optionflags)
 
723
                if isinstance(x, Example)]
 
724
 
 
725
    def _parse_example(self, m, name, lineno):
 
726
        """
 
727
        Given a regular expression match from `_EXAMPLE_RE` (`m`),
 
728
        return a pair `(source, want)`, where `source` is the matched
 
729
        example's source code (with prompts and indentation stripped);
 
730
        and `want` is the example's expected output (with indentation
 
731
        stripped).
 
732
 
 
733
        `name` is the string's name, and `lineno` is the line number
 
734
        where the example starts; both are used for error messages.
 
735
        """
 
736
        # Get the example's indentation level.
 
737
        indent = len(m.group('indent'))
 
738
 
 
739
        # Divide source into lines; check that they're properly
 
740
        # indented; and then strip their indentation & prompts.
 
741
        source_lines = m.group('source').split('\n')
 
742
        self._check_prompt_blank(source_lines, indent, name, lineno)
 
743
        self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno)
 
744
        source = '\n'.join([sl[indent+4:] for sl in source_lines])
 
745
 
 
746
        # Divide want into lines; check that it's properly indented; and
 
747
        # then strip the indentation.  Spaces before the last newline should
 
748
        # be preserved, so plain rstrip() isn't good enough.
 
749
        want = m.group('want')
 
750
        want_lines = want.split('\n')
 
751
        if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
 
752
            del want_lines[-1]  # forget final newline & spaces after it
 
753
        self._check_prefix(want_lines, ' '*indent, name,
 
754
                           lineno + len(source_lines))
 
755
        want = '\n'.join([wl[indent:] for wl in want_lines])
 
756
 
 
757
        # If `want` contains a traceback message, then extract it.
 
758
        m = self._EXCEPTION_RE.match(want)
 
759
        if m:
 
760
            exc_msg = m.group('msg')
 
761
        else:
 
762
            exc_msg = None
 
763
 
 
764
        # Extract options from the source.
 
765
        options = self._find_options(source, name, lineno)
 
766
 
 
767
        return source, options, want, exc_msg
 
768
 
 
769
    # This regular expression looks for option directives in the
 
770
    # source code of an example.  Option directives are comments
 
771
    # starting with "doctest:".  Warning: this may give false
 
772
    # positives for string-literals that contain the string
 
773
    # "#doctest:".  Eliminating these false positives would require
 
774
    # actually parsing the string; but we limit them by ignoring any
 
775
    # line containing "#doctest:" that is *followed* by a quote mark.
 
776
    _OPTION_DIRECTIVE_RE = re.compile(r'#\s*doctest:\s*([^\n\'"]*)$',
 
777
                                      re.MULTILINE)
 
778
 
 
779
    def _find_options(self, source, name, lineno):
 
780
        """
 
781
        Return a dictionary containing option overrides extracted from
 
782
        option directives in the given source string.
 
783
 
 
784
        `name` is the string's name, and `lineno` is the line number
 
785
        where the example starts; both are used for error messages.
 
786
        """
 
787
        options = {}
 
788
        # (note: with the current regexp, this will match at most once:)
 
789
        for m in self._OPTION_DIRECTIVE_RE.finditer(source):
 
790
            option_strings = m.group(1).replace(',', ' ').split()
 
791
            for option in option_strings:
 
792
                if (option[0] not in '+-' or
 
793
                    option[1:] not in OPTIONFLAGS_BY_NAME):
 
794
                    raise ValueError('line %r of the doctest for %s '
 
795
                                     'has an invalid option: %r' %
 
796
                                     (lineno+1, name, option))
 
797
                flag = OPTIONFLAGS_BY_NAME[option[1:]]
 
798
                options[flag] = (option[0] == '+')
 
799
        if options and self._IS_BLANK_OR_COMMENT(source):
 
800
            raise ValueError('line %r of the doctest for %s has an option '
 
801
                             'directive on a line with no example: %r' %
 
802
                             (lineno, name, source))
 
803
        return options
 
804
 
 
805
    # This regular expression finds the indentation of every non-blank
 
806
    # line in a string.
 
807
    _INDENT_RE = re.compile('^([ ]*)(?=\S)', re.MULTILINE)
 
808
 
 
809
    def _min_indent(self, s):
 
810
        "Return the minimum indentation of any non-blank line in `s`"
 
811
        indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
 
812
        if len(indents) > 0:
 
813
            return min(indents)
 
814
        else:
 
815
            return 0
 
816
 
 
817
    def _check_prompt_blank(self, lines, indent, name, lineno):
 
818
        """
 
819
        Given the lines of a source string (including prompts and
 
820
        leading indentation), check to make sure that every prompt is
 
821
        followed by a space character.  If any line is not followed by
 
822
        a space character, then raise ValueError.
 
823
        """
 
824
        for i, line in enumerate(lines):
 
825
            if len(line) >= indent+4 and line[indent+3] != ' ':
 
826
                raise ValueError('line %r of the docstring for %s '
 
827
                                 'lacks blank after %s: %r' %
 
828
                                 (lineno+i+1, name,
 
829
                                  line[indent:indent+3], line))
 
830
 
 
831
    def _check_prefix(self, lines, prefix, name, lineno):
 
832
        """
 
833
        Check that every line in the given list starts with the given
 
834
        prefix; if any line does not, then raise a ValueError.
 
835
        """
 
836
        for i, line in enumerate(lines):
 
837
            if line and not line.startswith(prefix):
 
838
                raise ValueError('line %r of the docstring for %s has '
 
839
                                 'inconsistent leading whitespace: %r' %
 
840
                                 (lineno+i+1, name, line))
 
841
 
 
842
 
 
843
######################################################################
 
844
## 4. DocTest Finder
 
845
######################################################################
 
846
 
 
847
class DocTestFinder:
 
848
    """
 
849
    A class used to extract the DocTests that are relevant to a given
 
850
    object, from its docstring and the docstrings of its contained
 
851
    objects.  Doctests can currently be extracted from the following
 
852
    object types: modules, functions, classes, methods, staticmethods,
 
853
    classmethods, and properties.
 
854
    """
 
855
 
 
856
    def __init__(self, verbose=False, parser=DocTestParser(),
 
857
                 recurse=True, _namefilter=None, exclude_empty=True):
 
858
        """
 
859
        Create a new doctest finder.
 
860
 
 
861
        The optional argument `parser` specifies a class or
 
862
        function that should be used to create new DocTest objects (or
 
863
        objects that implement the same interface as DocTest).  The
 
864
        signature for this factory function should match the signature
 
865
        of the DocTest constructor.
 
866
 
 
867
        If the optional argument `recurse` is false, then `find` will
 
868
        only examine the given object, and not any contained objects.
 
869
 
 
870
        If the optional argument `exclude_empty` is false, then `find`
 
871
        will include tests for objects with empty docstrings.
 
872
        """
 
873
        self._parser = parser
 
874
        self._verbose = verbose
 
875
        self._recurse = recurse
 
876
        self._exclude_empty = exclude_empty
 
877
        # _namefilter is undocumented, and exists only for temporary backward-
 
878
        # compatibility support of testmod's deprecated isprivate mess.
 
879
        self._namefilter = _namefilter
 
880
 
 
881
    def find(self, obj, name=None, module=None, globs=None,
 
882
             extraglobs=None, optionflags=0):
 
883
        """
 
884
        Return a list of the DocTests that are defined by the given
 
885
        object's docstring, or by any of its contained objects'
 
886
        docstrings.
 
887
 
 
888
        The optional parameter `module` is the module that contains
 
889
        the given object.  If the module is not specified or is None, then
 
890
        the test finder will attempt to automatically determine the
 
891
        correct module.  The object's module is used:
 
892
 
 
893
            - As a default namespace, if `globs` is not specified.
 
894
            - To prevent the DocTestFinder from extracting DocTests
 
895
              from objects that are imported from other modules.
 
896
            - To find the name of the file containing the object.
 
897
            - To help find the line number of the object within its
 
898
              file.
 
899
 
 
900
        Contained objects whose module does not match `module` are ignored.
 
901
 
 
902
        If `module` is False, no attempt to find the module will be made.
 
903
        This is obscure, of use mostly in tests:  if `module` is False, or
 
904
        is None but cannot be found automatically, then all objects are
 
905
        considered to belong to the (non-existent) module, so all contained
 
906
        objects will (recursively) be searched for doctests.
 
907
 
 
908
        The globals for each DocTest is formed by combining `globs`
 
909
        and `extraglobs` (bindings in `extraglobs` override bindings
 
910
        in `globs`).  A new copy of the globals dictionary is created
 
911
        for each DocTest.  If `globs` is not specified, then it
 
912
        defaults to the module's `__dict__`, if specified, or {}
 
913
        otherwise.  If `extraglobs` is not specified, then it defaults
 
914
        to {}.
 
915
 
 
916
        """
 
917
        # If name was not specified, then extract it from the object.
 
918
        if name is None:
 
919
            name = getattr(obj, '__name__', None)
 
920
            if name is None:
 
921
                raise ValueError("DocTestFinder.find: name must be given "
 
922
                        "when obj.__name__ doesn't exist: %r" %
 
923
                                 (type(obj),))
 
924
 
 
925
        # Find the module that contains the given object (if obj is
 
926
        # a module, then module=obj.).  Note: this may fail, in which
 
927
        # case module will be None.
 
928
        if module is False:
 
929
            module = None
 
930
        elif module is None:
 
931
            module = inspect.getmodule(obj)
 
932
 
 
933
        # Read the module's source code.  This is used by
 
934
        # DocTestFinder._find_lineno to find the line number for a
 
935
        # given object's docstring.
 
936
        try:
 
937
            file = inspect.getsourcefile(obj) or inspect.getfile(obj)
 
938
            source_lines = linecache.getlines(file)
 
939
            if not source_lines:
 
940
                source_lines = None
 
941
        except TypeError:
 
942
            source_lines = None
 
943
 
 
944
        # Initialize globals, and merge in extraglobs.
 
945
        if globs is None:
 
946
            if module is None:
 
947
                globs = {}
 
948
            else:
 
949
                globs = module.__dict__.copy()
 
950
        else:
 
951
            globs = globs.copy()
 
952
        if extraglobs is not None:
 
953
            globs.update(extraglobs)
 
954
 
 
955
        # Recursively expore `obj`, extracting DocTests.
 
956
        tests = []
 
957
        self._find(tests, obj, name, module, source_lines, globs, {},
 
958
                   optionflags=optionflags)
 
959
        return tests
 
960
 
 
961
    def _filter(self, obj, prefix, base):
 
962
        """
 
963
        Return true if the given object should not be examined.
 
964
        """
 
965
        return (self._namefilter is not None and
 
966
                self._namefilter(prefix, base))
 
967
 
 
968
    def _from_module(self, module, object):
 
969
        """
 
970
        Return true if the given object is defined in the given
 
971
        module.
 
972
        """
 
973
        if module is None:
 
974
            return True
 
975
        elif inspect.isfunction(object):
 
976
            return module.__dict__ is object.func_globals
 
977
        elif inspect.isclass(object):
 
978
            return module.__name__ == object.__module__
 
979
        elif inspect.getmodule(object) is not None:
 
980
            return module is inspect.getmodule(object)
 
981
        elif hasattr(object, '__module__'):
 
982
            return module.__name__ == object.__module__
 
983
        elif isinstance(object, property):
 
984
            return True # [XX] no way not be sure.
 
985
        else:
 
986
            raise ValueError("object must be a class or function")
 
987
 
 
988
    def _find(self, tests, obj, name, module, source_lines, globs, seen,
 
989
              optionflags):
 
990
        """
 
991
        Find tests for the given object and any contained objects, and
 
992
        add them to `tests`.
 
993
        """
 
994
        if self._verbose:
 
995
            print 'Finding tests in %s' % name
 
996
 
 
997
        # If we've already processed this object, then ignore it.
 
998
        if id(obj) in seen:
 
999
            return
 
1000
        seen[id(obj)] = 1
 
1001
 
 
1002
        # Find a test for this object, and add it to the list of tests.
 
1003
        test = self._get_test(obj, name, module, globs, source_lines,
 
1004
                              optionflags)
 
1005
        if test is not None:
 
1006
            tests.append(test)
 
1007
 
 
1008
        # Look for tests in a module's contained objects.
 
1009
        if inspect.ismodule(obj) and self._recurse:
 
1010
            for valname, val in obj.__dict__.items():
 
1011
                # Check if this contained object should be ignored.
 
1012
                if self._filter(val, name, valname):
 
1013
                    continue
 
1014
                valname = '%s.%s' % (name, valname)
 
1015
                # Recurse to functions & classes.
 
1016
                if ((inspect.isfunction(val) or inspect.isclass(val)) and
 
1017
                    self._from_module(module, val)):
 
1018
                    self._find(tests, val, valname, module, source_lines,
 
1019
                               globs, seen, optionflags)
 
1020
 
 
1021
        # Look for tests in a module's __test__ dictionary.
 
1022
        if inspect.ismodule(obj) and self._recurse:
 
1023
            for valname, val in getattr(obj, '__test__', {}).items():
 
1024
                if not isinstance(valname, basestring):
 
1025
                    raise ValueError("DocTestFinder.find: __test__ keys "
 
1026
                                     "must be strings: %r" %
 
1027
                                     (type(valname),))
 
1028
                if not (inspect.isfunction(val) or inspect.isclass(val) or
 
1029
                        inspect.ismethod(val) or inspect.ismodule(val) or
 
1030
                        isinstance(val, basestring)):
 
1031
                    raise ValueError("DocTestFinder.find: __test__ values "
 
1032
                                     "must be strings, functions, methods, "
 
1033
                                     "classes, or modules: %r" %
 
1034
                                     (type(val),))
 
1035
                valname = '%s.__test__.%s' % (name, valname)
 
1036
                self._find(tests, val, valname, module, source_lines,
 
1037
                           globs, seen, optionflags)
 
1038
 
 
1039
        # Look for tests in a class's contained objects.
 
1040
        if inspect.isclass(obj) and self._recurse:
 
1041
            for valname, val in obj.__dict__.items():
 
1042
                # Check if this contained object should be ignored.
 
1043
                if self._filter(val, name, valname):
 
1044
                    continue
 
1045
                # Special handling for staticmethod/classmethod.
 
1046
                if isinstance(val, staticmethod):
 
1047
                    val = getattr(obj, valname)
 
1048
                if isinstance(val, classmethod):
 
1049
                    val = getattr(obj, valname).im_func
 
1050
 
 
1051
                # Recurse to methods, properties, and nested classes.
 
1052
                if ((inspect.isfunction(val) or inspect.isclass(val) or
 
1053
                      isinstance(val, property)) and
 
1054
                      self._from_module(module, val)):
 
1055
                    valname = '%s.%s' % (name, valname)
 
1056
                    self._find(tests, val, valname, module, source_lines,
 
1057
                               globs, seen, optionflags)
 
1058
 
 
1059
    def _get_test(self, obj, name, module, globs, source_lines, optionflags):
 
1060
        """
 
1061
        Return a DocTest for the given object, if it defines a docstring;
 
1062
        otherwise, return None.
 
1063
        """
 
1064
        # Extract the object's docstring.  If it doesn't have one,
 
1065
        # then return None (no test for this object).
 
1066
        if isinstance(obj, basestring):
 
1067
            docstring = obj
 
1068
        else:
 
1069
            try:
 
1070
                if obj.__doc__ is None:
 
1071
                    docstring = ''
 
1072
                else:
 
1073
                    docstring = obj.__doc__
 
1074
                    if not isinstance(docstring, basestring):
 
1075
                        docstring = str(docstring)
 
1076
            except (TypeError, AttributeError):
 
1077
                docstring = ''
 
1078
 
 
1079
        # Find the docstring's location in the file.
 
1080
        lineno = self._find_lineno(obj, source_lines)
 
1081
 
 
1082
        # Don't bother if the docstring is empty.
 
1083
        if self._exclude_empty and not docstring:
 
1084
            return None
 
1085
 
 
1086
        # Return a DocTest for this object.
 
1087
        if module is None:
 
1088
            filename = None
 
1089
        else:
 
1090
            filename = getattr(module, '__file__', module.__name__)
 
1091
            if filename[-4:] in (".pyc", ".pyo"):
 
1092
                filename = filename[:-1]
 
1093
        return self._parser.get_doctest(docstring, globs, name,
 
1094
                                        filename, lineno, optionflags)
 
1095
 
 
1096
    def _find_lineno(self, obj, source_lines):
 
1097
        """
 
1098
        Return a line number of the given object's docstring.  Note:
 
1099
        this method assumes that the object has a docstring.
 
1100
        """
 
1101
        lineno = None
 
1102
 
 
1103
        # Find the line number for modules.
 
1104
        if inspect.ismodule(obj):
 
1105
            lineno = 0
 
1106
 
 
1107
        # Find the line number for classes.
 
1108
        # Note: this could be fooled if a class is defined multiple
 
1109
        # times in a single file.
 
1110
        if inspect.isclass(obj):
 
1111
            if source_lines is None:
 
1112
                return None
 
1113
            pat = re.compile(r'^\s*class\s*%s\b' %
 
1114
                             getattr(obj, '__name__', '-'))
 
1115
            for i, line in enumerate(source_lines):
 
1116
                if pat.match(line):
 
1117
                    lineno = i
 
1118
                    break
 
1119
 
 
1120
        # Find the line number for functions & methods.
 
1121
        if inspect.ismethod(obj): obj = obj.im_func
 
1122
        if inspect.isfunction(obj): obj = obj.func_code
 
1123
        if inspect.istraceback(obj): obj = obj.tb_frame
 
1124
        if inspect.isframe(obj): obj = obj.f_code
 
1125
        if inspect.iscode(obj):
 
1126
            lineno = getattr(obj, 'co_firstlineno', None)-1
 
1127
 
 
1128
        # Find the line number where the docstring starts.  Assume
 
1129
        # that it's the first line that begins with a quote mark.
 
1130
        # Note: this could be fooled by a multiline function
 
1131
        # signature, where a continuation line begins with a quote
 
1132
        # mark.
 
1133
        if lineno is not None:
 
1134
            if source_lines is None:
 
1135
                return lineno+1
 
1136
            pat = re.compile('(^|.*:)\s*\w*("|\')')
 
1137
            for lineno in range(lineno, len(source_lines)):
 
1138
                if pat.match(source_lines[lineno]):
 
1139
                    return lineno
 
1140
 
 
1141
        # We couldn't find the line number.
 
1142
        return None
 
1143
 
 
1144
######################################################################
 
1145
## 5. DocTest Runner
 
1146
######################################################################
 
1147
 
 
1148
class DocTestRunner:
 
1149
    """
 
1150
    A class used to run DocTest test cases, and accumulate statistics.
 
1151
    The `run` method is used to process a single DocTest case.  It
 
1152
    returns a tuple `(f, t)`, where `t` is the number of test cases
 
1153
    tried, and `f` is the number of test cases that failed.
 
1154
 
 
1155
        >>> tests = DocTestFinder().find(_TestClass)
 
1156
        >>> runner = DocTestRunner(verbose=False)
 
1157
        >>> for test in tests:
 
1158
        ...     print runner.run(test)
 
1159
        (0, 2)
 
1160
        (0, 1)
 
1161
        (0, 2)
 
1162
        (0, 2)
 
1163
 
 
1164
    The `summarize` method prints a summary of all the test cases that
 
1165
    have been run by the runner, and returns an aggregated `(f, t)`
 
1166
    tuple:
 
1167
 
 
1168
        >>> runner.summarize(verbose=1)
 
1169
        4 items passed all tests:
 
1170
           2 tests in _TestClass
 
1171
           2 tests in _TestClass.__init__
 
1172
           2 tests in _TestClass.get
 
1173
           1 tests in _TestClass.square
 
1174
        7 tests in 4 items.
 
1175
        7 passed and 0 failed.
 
1176
        Test passed.
 
1177
        (0, 7)
 
1178
 
 
1179
    The aggregated number of tried examples and failed examples is
 
1180
    also available via the `tries` and `failures` attributes:
 
1181
 
 
1182
        >>> runner.tries
 
1183
        7
 
1184
        >>> runner.failures
 
1185
        0
 
1186
 
 
1187
    The comparison between expected outputs and actual outputs is done
 
1188
    by an `OutputChecker`.  This comparison may be customized with a
 
1189
    number of option flags; see the documentation for `testmod` for
 
1190
    more information.  If the option flags are insufficient, then the
 
1191
    comparison may also be customized by passing a subclass of
 
1192
    `OutputChecker` to the constructor.
 
1193
 
 
1194
    The test runner's display output can be controlled in two ways.
 
1195
    First, an output function (`out) can be passed to
 
1196
    `TestRunner.run`; this function will be called with strings that
 
1197
    should be displayed.  It defaults to `sys.stdout.write`.  If
 
1198
    capturing the output is not sufficient, then the display output
 
1199
    can be also customized by subclassing DocTestRunner, and
 
1200
    overriding the methods `report_start`, `report_success`,
 
1201
    `report_unexpected_exception`, and `report_failure`.
 
1202
    """
 
1203
    # This divider string is used to separate failure messages, and to
 
1204
    # separate sections of the summary.
 
1205
    DIVIDER = "*" * 70
 
1206
 
 
1207
    def __init__(self, checker=None, verbose=None, optionflags=0):
 
1208
        """
 
1209
        Create a new test runner.
 
1210
 
 
1211
        Optional keyword arg `checker` is the `OutputChecker` that
 
1212
        should be used to compare the expected outputs and actual
 
1213
        outputs of doctest examples.
 
1214
 
 
1215
        Optional keyword arg 'verbose' prints lots of stuff if true,
 
1216
        only failures if false; by default, it's true iff '-v' is in
 
1217
        sys.argv.
 
1218
 
 
1219
        Optional argument `optionflags` can be used to control how the
 
1220
        test runner compares expected output to actual output, and how
 
1221
        it displays failures.  See the documentation for `testmod` for
 
1222
        more information.
 
1223
        """
 
1224
        self._checker = checker or OutputChecker()
 
1225
        if verbose is None:
 
1226
            verbose = '-v' in sys.argv
 
1227
        self._verbose = verbose
 
1228
        self.optionflags = optionflags
 
1229
        self.original_optionflags = optionflags
 
1230
 
 
1231
        # Keep track of the examples we've run.
 
1232
        self.tries = 0
 
1233
        self.failures = 0
 
1234
        self._name2ft = {}
 
1235
 
 
1236
        # Create a fake output target for capturing doctest output.
 
1237
        self._fakeout = _SpoofOut()
 
1238
 
 
1239
    #/////////////////////////////////////////////////////////////////
 
1240
    # Reporting methods
 
1241
    #/////////////////////////////////////////////////////////////////
 
1242
 
 
1243
    def report_start(self, out, test, example):
 
1244
        """
 
1245
        Report that the test runner is about to process the given
 
1246
        example.  (Only displays a message if verbose=True)
 
1247
        """
 
1248
        if self._verbose:
 
1249
            if example.want:
 
1250
                out('Trying:\n' + _indent(example.source) +
 
1251
                    'Expecting:\n' + _indent(example.want))
 
1252
            else:
 
1253
                out('Trying:\n' + _indent(example.source) +
 
1254
                    'Expecting nothing\n')
 
1255
 
 
1256
    def report_success(self, out, test, example, got):
 
1257
        """
 
1258
        Report that the given example ran successfully.  (Only
 
1259
        displays a message if verbose=True)
 
1260
        """
 
1261
        if self._verbose:
 
1262
            out("ok\n")
 
1263
 
 
1264
    def report_failure(self, out, test, example, got):
 
1265
        """
 
1266
        Report that the given example failed.
 
1267
        """
 
1268
        out(self._failure_header(test, example) +
 
1269
            self._checker.output_difference(example, got, self.optionflags))
 
1270
 
 
1271
    def report_unexpected_exception(self, out, test, example, exc_info):
 
1272
        """
 
1273
        Report that the given example raised an unexpected exception.
 
1274
        """
 
1275
        out(self._failure_header(test, example) +
 
1276
            'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
 
1277
 
 
1278
    def _failure_header(self, test, example):
 
1279
        out = [self.DIVIDER]
 
1280
        if test.filename:
 
1281
            if test.lineno is not None and example.lineno is not None:
 
1282
                lineno = test.lineno + example.lineno + 1
 
1283
            else:
 
1284
                lineno = '?'
 
1285
            out.append('File "%s", line %s, in %s' %
 
1286
                       (test.filename, lineno, test.name))
 
1287
        else:
 
1288
            out.append('Line %s, in %s' % (example.lineno+1, test.name))
 
1289
        out.append('Failed example:')
 
1290
        source = example.source
 
1291
        out.append(_indent(source))
 
1292
        return '\n'.join(out)
 
1293
 
 
1294
    #/////////////////////////////////////////////////////////////////
 
1295
    # DocTest Running
 
1296
    #/////////////////////////////////////////////////////////////////
 
1297
 
 
1298
    def __run(self, test, compileflags, out):
 
1299
        """
 
1300
        Run the examples in `test`.  Write the outcome of each example
 
1301
        with one of the `DocTestRunner.report_*` methods, using the
 
1302
        writer function `out`.  `compileflags` is the set of compiler
 
1303
        flags that should be used to execute examples.  Return a tuple
 
1304
        `(f, t)`, where `t` is the number of examples tried, and `f`
 
1305
        is the number of examples that failed.  The examples are run
 
1306
        in the namespace `test.globs`.
 
1307
        """
 
1308
        # Keep track of the number of failures and tries.
 
1309
        failures = tries = 0
 
1310
 
 
1311
        # Save the option flags (since option directives can be used
 
1312
        # to modify them).
 
1313
        original_optionflags = self.optionflags
 
1314
 
 
1315
        SUCCESS, FAILURE, BOOM = range(3) # `outcome` state
 
1316
 
 
1317
        check = self._checker.check_output
 
1318
 
 
1319
        # Process each example.
 
1320
        for examplenum, example in enumerate(test.examples):
 
1321
 
 
1322
            # If REPORT_ONLY_FIRST_FAILURE is set, then supress
 
1323
            # reporting after the first failure.
 
1324
            quiet = (self.optionflags & REPORT_ONLY_FIRST_FAILURE and
 
1325
                     failures > 0)
 
1326
 
 
1327
            # Merge in the example's options.
 
1328
            self.optionflags = original_optionflags
 
1329
            if example.options:
 
1330
                for (optionflag, val) in example.options.items():
 
1331
                    if val:
 
1332
                        self.optionflags |= optionflag
 
1333
                    else:
 
1334
                        self.optionflags &= ~optionflag
 
1335
 
 
1336
            # Record that we started this example.
 
1337
            tries += 1
 
1338
            if not quiet:
 
1339
                self.report_start(out, test, example)
 
1340
 
 
1341
            # Use a special filename for compile(), so we can retrieve
 
1342
            # the source code during interactive debugging (see
 
1343
            # __patched_linecache_getlines).
 
1344
            # Line number counting starts with 0 so we add one to get
 
1345
            # the real line number.
 
1346
            filename = '<doctest %s[line %d, example %d]>' % (
 
1347
                test.name, example.lineno+1, examplenum)
 
1348
 
 
1349
            # Run the example in the given context (globs), and record
 
1350
            # any exception that gets raised.  (But don't intercept
 
1351
            # keyboard interrupts.)
 
1352
            try:
 
1353
                # Don't blink!  This is where the user's code gets run.
 
1354
                exec compile(example.source, filename, "single",
 
1355
                             compileflags, 1) in test.globs
 
1356
                self.debugger.set_continue() # ==== Example Finished ====
 
1357
                exception = None
 
1358
            except KeyboardInterrupt:
 
1359
                raise
 
1360
            except:
 
1361
                exception = sys.exc_info()
 
1362
                self.debugger.set_continue() # ==== Example Finished ====
 
1363
            got = self._fakeout.getvalue()  # the actual output
 
1364
            self._fakeout.truncate(0)
 
1365
            outcome = FAILURE   # guilty until proved innocent or insane
 
1366
 
 
1367
            # If the example executed without raising any exceptions,
 
1368
            # verify its output.
 
1369
            if exception is None:
 
1370
                if check(example.want, got, self.optionflags):
 
1371
                    outcome = SUCCESS
 
1372
 
 
1373
            # The example raised an exception:  check if it was expected.
 
1374
            else:
 
1375
                exc_info = sys.exc_info()
 
1376
                exc_msg = traceback.format_exception_only(*exc_info[:2])[-1]
 
1377
                if not quiet:
 
1378
                    got += _exception_traceback(exc_info)
 
1379
 
 
1380
                # If `example.exc_msg` is None, then we weren't expecting
 
1381
                # an exception.
 
1382
                if example.exc_msg is None:
 
1383
                    outcome = BOOM
 
1384
 
 
1385
                # We expected an exception:  see whether it matches.
 
1386
                elif check(example.exc_msg, exc_msg, self.optionflags):
 
1387
                    outcome = SUCCESS
 
1388
 
 
1389
                # Another chance if they didn't care about the detail.
 
1390
                elif self.optionflags & IGNORE_EXCEPTION_DETAIL:
 
1391
                    m1 = re.match(r'[^:]*:', example.exc_msg)
 
1392
                    m2 = re.match(r'[^:]*:', exc_msg)
 
1393
                    if m1 and m2 and check(m1.group(0), m2.group(0),
 
1394
                                           self.optionflags):
 
1395
                        outcome = SUCCESS
 
1396
 
 
1397
            # Report the outcome.
 
1398
            if outcome is SUCCESS:
 
1399
                if not quiet:
 
1400
                    self.report_success(out, test, example, got)
 
1401
            elif outcome is FAILURE:
 
1402
                if not quiet:
 
1403
                    self.report_failure(out, test, example, got)
 
1404
                failures += 1
 
1405
            elif outcome is BOOM:
 
1406
                if not quiet:
 
1407
                    self.report_unexpected_exception(out, test, example,
 
1408
                                                     exc_info)
 
1409
                failures += 1
 
1410
            else:
 
1411
                assert False, ("unknown outcome", outcome)
 
1412
 
 
1413
        # Restore the option flags (in case they were modified)
 
1414
        self.optionflags = original_optionflags
 
1415
 
 
1416
        # Record and return the number of failures and tries.
 
1417
        self.__record_outcome(test, failures, tries)
 
1418
        return failures, tries
 
1419
 
 
1420
    def __record_outcome(self, test, f, t):
 
1421
        """
 
1422
        Record the fact that the given DocTest (`test`) generated `f`
 
1423
        failures out of `t` tried examples.
 
1424
        """
 
1425
        f2, t2 = self._name2ft.get(test.name, (0,0))
 
1426
        self._name2ft[test.name] = (f+f2, t+t2)
 
1427
        self.failures += f
 
1428
        self.tries += t
 
1429
 
 
1430
    __LINECACHE_FILENAME_RE = re.compile(
 
1431
        r'<doctest (?P<name>[\w\.]+)\[line \d+, example (?P<examplenum>\d+)\]>$'
 
1432
        )
 
1433
 
 
1434
    def __patched_linecache_getlines(self, filename, module_globals=None):
 
1435
        m = self.__LINECACHE_FILENAME_RE.match(filename)
 
1436
        if m and m.group('name') == self.test.name:
 
1437
            example = self.test.examples[int(m.group('examplenum'))]
 
1438
            return example.source.splitlines(True)
 
1439
        else:
 
1440
            if module_globals is None:
 
1441
                return self.save_linecache_getlines(filename)
 
1442
            else:
 
1443
                return self.save_linecache_getlines(filename, module_globals)
 
1444
 
 
1445
    def run(self, test, compileflags=None, out=None, clear_globs=True):
 
1446
        """
 
1447
        Run the examples in `test`, and display the results using the
 
1448
        writer function `out`.
 
1449
 
 
1450
        The examples are run in the namespace `test.globs`.  If
 
1451
        `clear_globs` is true (the default), then this namespace will
 
1452
        be cleared after the test runs, to help with garbage
 
1453
        collection.  If you would like to examine the namespace after
 
1454
        the test completes, then use `clear_globs=False`.
 
1455
 
 
1456
        `compileflags` gives the set of flags that should be used by
 
1457
        the Python compiler when running the examples.  If not
 
1458
        specified, then it will default to the set of future-import
 
1459
        flags that apply to `globs`.
 
1460
 
 
1461
        The output of each example is checked using
 
1462
        `DocTestRunner.check_output`, and the results are formatted by
 
1463
        the `DocTestRunner.report_*` methods.
 
1464
        """
 
1465
        self.test = test
 
1466
 
 
1467
        if compileflags is None:
 
1468
            compileflags = _extract_future_flags(test.globs)
 
1469
 
 
1470
        save_stdout = sys.stdout
 
1471
        if out is None:
 
1472
            out = save_stdout.write
 
1473
        sys.stdout = self._fakeout
 
1474
 
 
1475
        # Patch pdb.set_trace to restore sys.stdout during interactive
 
1476
        # debugging (so it's not still redirected to self._fakeout).
 
1477
        # Note that the interactive output will go to *our*
 
1478
        # save_stdout, even if that's not the real sys.stdout; this
 
1479
        # allows us to write test cases for the set_trace behavior.
 
1480
        save_set_trace = pdb.set_trace
 
1481
        self.debugger = _OutputRedirectingPdb(save_stdout)
 
1482
        self.debugger.reset()
 
1483
        pdb.set_trace = self.debugger.set_trace
 
1484
 
 
1485
        # Patch linecache.getlines, so we can see the example's source
 
1486
        # when we're inside the debugger.
 
1487
        self.save_linecache_getlines = linecache.getlines
 
1488
        linecache.getlines = self.__patched_linecache_getlines
 
1489
 
 
1490
        try:
 
1491
            return self.__run(test, compileflags, out)
 
1492
        finally:
 
1493
            sys.stdout = save_stdout
 
1494
            pdb.set_trace = save_set_trace
 
1495
            linecache.getlines = self.save_linecache_getlines
 
1496
            if clear_globs:
 
1497
                test.globs.clear()
 
1498
 
 
1499
    #/////////////////////////////////////////////////////////////////
 
1500
    # Summarization
 
1501
    #/////////////////////////////////////////////////////////////////
 
1502
    def summarize(self, verbose=None):
 
1503
        """
 
1504
        Print a summary of all the test cases that have been run by
 
1505
        this DocTestRunner, and return a tuple `(f, t)`, where `f` is
 
1506
        the total number of failed examples, and `t` is the total
 
1507
        number of tried examples.
 
1508
 
 
1509
        The optional `verbose` argument controls how detailed the
 
1510
        summary is.  If the verbosity is not specified, then the
 
1511
        DocTestRunner's verbosity is used.
 
1512
        """
 
1513
        if verbose is None:
 
1514
            verbose = self._verbose
 
1515
        notests = []
 
1516
        passed = []
 
1517
        failed = []
 
1518
        totalt = totalf = 0
 
1519
        for x in self._name2ft.items():
 
1520
            name, (f, t) = x
 
1521
            assert f <= t
 
1522
            totalt += t
 
1523
            totalf += f
 
1524
            if t == 0:
 
1525
                notests.append(name)
 
1526
            elif f == 0:
 
1527
                passed.append( (name, t) )
 
1528
            else:
 
1529
                failed.append(x)
 
1530
        if verbose:
 
1531
            if notests:
 
1532
                print len(notests), "items had no tests:"
 
1533
                notests.sort()
 
1534
                for thing in notests:
 
1535
                    print "   ", thing
 
1536
            if passed:
 
1537
                print len(passed), "items passed all tests:"
 
1538
                passed.sort()
 
1539
                for thing, count in passed:
 
1540
                    print " %3d tests in %s" % (count, thing)
 
1541
        if failed:
 
1542
            print self.DIVIDER
 
1543
            print len(failed), "items had failures:"
 
1544
            failed.sort()
 
1545
            for thing, (f, t) in failed:
 
1546
                print " %3d of %3d in %s" % (f, t, thing)
 
1547
        if verbose:
 
1548
            print totalt, "tests in", len(self._name2ft), "items."
 
1549
            print totalt - totalf, "passed and", totalf, "failed."
 
1550
        if totalf:
 
1551
            print "***Test Failed***", totalf, "failures."
 
1552
        elif verbose:
 
1553
            print "Test passed."
 
1554
        return totalf, totalt
 
1555
 
 
1556
    #/////////////////////////////////////////////////////////////////
 
1557
    # Backward compatibility cruft to maintain doctest.master.
 
1558
    #/////////////////////////////////////////////////////////////////
 
1559
    def merge(self, other):
 
1560
        d = self._name2ft
 
1561
        for name, (f, t) in other._name2ft.items():
 
1562
            if name in d:
 
1563
                print "*** DocTestRunner.merge: '" + name + "' in both" \
 
1564
                    " testers; summing outcomes."
 
1565
                f2, t2 = d[name]
 
1566
                f = f + f2
 
1567
                t = t + t2
 
1568
            d[name] = f, t
 
1569
 
 
1570
class OutputChecker:
 
1571
    """
 
1572
    A class used to check the whether the actual output from a doctest
 
1573
    example matches the expected output.  `OutputChecker` defines two
 
1574
    methods: `check_output`, which compares a given pair of outputs,
 
1575
    and returns true if they match; and `output_difference`, which
 
1576
    returns a string describing the differences between two outputs.
 
1577
    """
 
1578
    def check_output(self, want, got, optionflags):
 
1579
        """
 
1580
        Return True iff the actual output from an example (`got`)
 
1581
        matches the expected output (`want`).  These strings are
 
1582
        always considered to match if they are identical; but
 
1583
        depending on what option flags the test runner is using,
 
1584
        several non-exact match types are also possible.  See the
 
1585
        documentation for `TestRunner` for more information about
 
1586
        option flags.
 
1587
        """
 
1588
        # Handle the common case first, for efficiency:
 
1589
        # if they're string-identical, always return true.
 
1590
        if got == want:
 
1591
            return True
 
1592
 
 
1593
        # The values True and False replaced 1 and 0 as the return
 
1594
        # value for boolean comparisons in Python 2.3.
 
1595
        if not (optionflags & DONT_ACCEPT_TRUE_FOR_1):
 
1596
            if (got,want) == ("True\n", "1\n"):
 
1597
                return True
 
1598
            if (got,want) == ("False\n", "0\n"):
 
1599
                return True
 
1600
 
 
1601
        # <BLANKLINE> can be used as a special sequence to signify a
 
1602
        # blank line, unless the DONT_ACCEPT_BLANKLINE flag is used.
 
1603
        if not (optionflags & DONT_ACCEPT_BLANKLINE):
 
1604
            # Replace <BLANKLINE> in want with a blank line.
 
1605
            want = re.sub('(?m)^%s\s*?$' % re.escape(BLANKLINE_MARKER),
 
1606
                          '', want)
 
1607
            # If a line in got contains only spaces, then remove the
 
1608
            # spaces.
 
1609
            got = re.sub('(?m)^\s*?$', '', got)
 
1610
            if got == want:
 
1611
                return True
 
1612
 
 
1613
        # This flag causes doctest to ignore any differences in the
 
1614
        # contents of whitespace strings.  Note that this can be used
 
1615
        # in conjunction with the ELLIPSIS flag.
 
1616
        if optionflags & NORMALIZE_WHITESPACE:
 
1617
            got = ' '.join(got.split())
 
1618
            want = ' '.join(want.split())
 
1619
            if got == want:
 
1620
                return True
 
1621
 
 
1622
        # The ELLIPSIS flag says to let the sequence "..." in `want`
 
1623
        # match any substring in `got`.
 
1624
        if optionflags & ELLIPSIS:
 
1625
            if _ellipsis_match(want, got):
 
1626
                return True
 
1627
 
 
1628
        # We didn't find any match; return false.
 
1629
        return False
 
1630
 
 
1631
    # Should we do a fancy diff?
 
1632
    def _do_a_fancy_diff(self, want, got, optionflags):
 
1633
        # Not unless they asked for a fancy diff.
 
1634
        if not optionflags & (REPORT_UDIFF |
 
1635
                              REPORT_CDIFF |
 
1636
                              REPORT_NDIFF):
 
1637
            return False
 
1638
 
 
1639
        # If expected output uses ellipsis, a meaningful fancy diff is
 
1640
        # too hard ... or maybe not.  In two real-life failures Tim saw,
 
1641
        # a diff was a major help anyway, so this is commented out.
 
1642
        # [todo] _ellipsis_match() knows which pieces do and don't match,
 
1643
        # and could be the basis for a kick-ass diff in this case.
 
1644
        ##if optionflags & ELLIPSIS and ELLIPSIS_MARKER in want:
 
1645
        ##    return False
 
1646
 
 
1647
        # ndiff does intraline difference marking, so can be useful even
 
1648
        # for 1-line differences.
 
1649
        if optionflags & REPORT_NDIFF:
 
1650
            return True
 
1651
 
 
1652
        # The other diff types need at least a few lines to be helpful.
 
1653
        return want.count('\n') > 2 and got.count('\n') > 2
 
1654
 
 
1655
    def output_difference(self, example, got, optionflags):
 
1656
        """
 
1657
        Return a string describing the differences between the
 
1658
        expected output for a given example (`example`) and the actual
 
1659
        output (`got`).  `optionflags` is the set of option flags used
 
1660
        to compare `want` and `got`.
 
1661
        """
 
1662
        want = example.want
 
1663
        # If <BLANKLINE>s are being used, then replace blank lines
 
1664
        # with <BLANKLINE> in the actual output string.
 
1665
        if not (optionflags & DONT_ACCEPT_BLANKLINE):
 
1666
            got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
 
1667
 
 
1668
        # Check if we should use diff.
 
1669
        if self._do_a_fancy_diff(want, got, optionflags):
 
1670
            # Split want & got into lines.
 
1671
            want_lines = want.splitlines(True)  # True == keep line ends
 
1672
            got_lines = got.splitlines(True)
 
1673
            # Use difflib to find their differences.
 
1674
            if optionflags & REPORT_UDIFF:
 
1675
                diff = difflib.unified_diff(want_lines, got_lines, n=2)
 
1676
                diff = list(diff)[2:] # strip the diff header
 
1677
                kind = 'unified diff with -expected +actual'
 
1678
            elif optionflags & REPORT_CDIFF:
 
1679
                diff = difflib.context_diff(want_lines, got_lines, n=2)
 
1680
                diff = list(diff)[2:] # strip the diff header
 
1681
                kind = 'context diff with expected followed by actual'
 
1682
            elif optionflags & REPORT_NDIFF:
 
1683
                engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK)
 
1684
                diff = list(engine.compare(want_lines, got_lines))
 
1685
                kind = 'ndiff with -expected +actual'
 
1686
            else:
 
1687
                assert 0, 'Bad diff option'
 
1688
            # Remove trailing whitespace on diff output.
 
1689
            diff = [line.rstrip() + '\n' for line in diff]
 
1690
            return 'Differences (%s):\n' % kind + _indent(''.join(diff))
 
1691
 
 
1692
        # If we're not using diff, then simply list the expected
 
1693
        # output followed by the actual output.
 
1694
        if want and got:
 
1695
            return 'Expected:\n%sGot:\n%s' % (_indent(want), _indent(got))
 
1696
        elif want:
 
1697
            return 'Expected:\n%sGot nothing\n' % _indent(want)
 
1698
        elif got:
 
1699
            return 'Expected nothing\nGot:\n%s' % _indent(got)
 
1700
        else:
 
1701
            return 'Expected nothing\nGot nothing\n'
 
1702
 
 
1703
 
 
1704
class DebugRunner(DocTestRunner):
 
1705
    r"""Run doc tests but raise an exception as soon as there is a failure.
 
1706
 
 
1707
       If an unexpected exception occurs, an UnexpectedException is raised.
 
1708
       It contains the test, the example, and the original exception:
 
1709
 
 
1710
         >>> runner = DebugRunner(verbose=False)
 
1711
         >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
 
1712
         ...                                    {}, 'foo', 'foo.py', 0)
 
1713
         >>> try:
 
1714
         ...     runner.run(test)
 
1715
         ... except UnexpectedException, failure:
 
1716
         ...     pass
 
1717
 
 
1718
         >>> failure.test is test
 
1719
         True
 
1720
 
 
1721
         >>> failure.example.want
 
1722
         '42\n'
 
1723
 
 
1724
         >>> exc_info = failure.exc_info
 
1725
         >>> raise exc_info[0], exc_info[1], exc_info[2]
 
1726
         Traceback (most recent call last):
 
1727
         ...
 
1728
         KeyError
 
1729
 
 
1730
       We wrap the original exception to give the calling application
 
1731
       access to the test and example information.
 
1732
 
 
1733
       If the output doesn't match, then a DocTestFailure is raised:
 
1734
 
 
1735
         >>> test = DocTestParser().get_doctest('''
 
1736
         ...      >>> x = 1
 
1737
         ...      >>> x
 
1738
         ...      2
 
1739
         ...      ''', {}, 'foo', 'foo.py', 0)
 
1740
 
 
1741
         >>> try:
 
1742
         ...    runner.run(test)
 
1743
         ... except DocTestFailure, failure:
 
1744
         ...    pass
 
1745
 
 
1746
       DocTestFailure objects provide access to the test:
 
1747
 
 
1748
         >>> failure.test is test
 
1749
         True
 
1750
 
 
1751
       As well as to the example:
 
1752
 
 
1753
         >>> failure.example.want
 
1754
         '2\n'
 
1755
 
 
1756
       and the actual output:
 
1757
 
 
1758
         >>> failure.got
 
1759
         '1\n'
 
1760
 
 
1761
       If a failure or error occurs, the globals are left intact:
 
1762
 
 
1763
         >>> del test.globs['__builtins__']
 
1764
         >>> test.globs
 
1765
         {'x': 1}
 
1766
 
 
1767
         >>> test = DocTestParser().get_doctest('''
 
1768
         ...      >>> x = 2
 
1769
         ...      >>> raise KeyError
 
1770
         ...      ''', {}, 'foo', 'foo.py', 0)
 
1771
 
 
1772
         >>> runner.run(test)
 
1773
         Traceback (most recent call last):
 
1774
         ...
 
1775
         UnexpectedException: <DocTest foo from foo.py:0 (2 examples)>
 
1776
 
 
1777
         >>> del test.globs['__builtins__']
 
1778
         >>> test.globs
 
1779
         {'x': 2}
 
1780
 
 
1781
       But the globals are cleared if there is no error:
 
1782
 
 
1783
         >>> test = DocTestParser().get_doctest('''
 
1784
         ...      >>> x = 2
 
1785
         ...      ''', {}, 'foo', 'foo.py', 0)
 
1786
 
 
1787
         >>> runner.run(test)
 
1788
         (0, 1)
 
1789
 
 
1790
         >>> test.globs
 
1791
         {}
 
1792
 
 
1793
       """
 
1794
 
 
1795
    def run(self, test, compileflags=None, out=None, clear_globs=True):
 
1796
        r = DocTestRunner.run(self, test, compileflags, out, False)
 
1797
        if clear_globs:
 
1798
            test.globs.clear()
 
1799
        return r
 
1800
 
 
1801
    def report_unexpected_exception(self, out, test, example, exc_info):
 
1802
        raise UnexpectedException(test, example, exc_info)
 
1803
 
 
1804
    def report_failure(self, out, test, example, got):
 
1805
        raise DocTestFailure(test, example, got)
 
1806
 
 
1807
######################################################################
 
1808
## 6. Test Functions
 
1809
######################################################################
 
1810
# These should be backwards compatible.
 
1811
 
 
1812
# For backward compatibility, a global instance of a DocTestRunner
 
1813
# class, updated by testmod.
 
1814
master = None
 
1815
 
 
1816
def testmod(m=None, name=None, globs=None, verbose=None, isprivate=None,
 
1817
            report=True, optionflags=0, extraglobs=None,
 
1818
            raise_on_error=False, exclude_empty=False):
 
1819
    """m=None, name=None, globs=None, verbose=None, isprivate=None,
 
1820
       report=True, optionflags=0, extraglobs=None, raise_on_error=False,
 
1821
       exclude_empty=False
 
1822
 
 
1823
    Test examples in docstrings in functions and classes reachable
 
1824
    from module m (or the current module if m is not supplied), starting
 
1825
    with m.__doc__.  Unless isprivate is specified, private names
 
1826
    are not skipped.
 
1827
 
 
1828
    Also test examples reachable from dict m.__test__ if it exists and is
 
1829
    not None.  m.__test__ maps names to functions, classes and strings;
 
1830
    function and class docstrings are tested even if the name is private;
 
1831
    strings are tested directly, as if they were docstrings.
 
1832
 
 
1833
    Return (#failures, #tests).
 
1834
 
 
1835
    See doctest.__doc__ for an overview.
 
1836
 
 
1837
    Optional keyword arg "name" gives the name of the module; by default
 
1838
    use m.__name__.
 
1839
 
 
1840
    Optional keyword arg "globs" gives a dict to be used as the globals
 
1841
    when executing examples; by default, use m.__dict__.  A copy of this
 
1842
    dict is actually used for each docstring, so that each docstring's
 
1843
    examples start with a clean slate.
 
1844
 
 
1845
    Optional keyword arg "extraglobs" gives a dictionary that should be
 
1846
    merged into the globals that are used to execute examples.  By
 
1847
    default, no extra globals are used.  This is new in 2.4.
 
1848
 
 
1849
    Optional keyword arg "verbose" prints lots of stuff if true, prints
 
1850
    only failures if false; by default, it's true iff "-v" is in sys.argv.
 
1851
 
 
1852
    Optional keyword arg "report" prints a summary at the end when true,
 
1853
    else prints nothing at the end.  In verbose mode, the summary is
 
1854
    detailed, else very brief (in fact, empty if all tests passed).
 
1855
 
 
1856
    Optional keyword arg "optionflags" or's together module constants,
 
1857
    and defaults to 0.  This is new in 2.3.  Possible values (see the
 
1858
    docs for details):
 
1859
 
 
1860
        DONT_ACCEPT_TRUE_FOR_1
 
1861
        DONT_ACCEPT_BLANKLINE
 
1862
        NORMALIZE_WHITESPACE
 
1863
        ELLIPSIS
 
1864
        IGNORE_EXCEPTION_DETAIL
 
1865
        REPORT_UDIFF
 
1866
        REPORT_CDIFF
 
1867
        REPORT_NDIFF
 
1868
        REPORT_ONLY_FIRST_FAILURE
 
1869
 
 
1870
    Optional keyword arg "raise_on_error" raises an exception on the
 
1871
    first unexpected exception or failure. This allows failures to be
 
1872
    post-mortem debugged.
 
1873
 
 
1874
    Deprecated in Python 2.4:
 
1875
    Optional keyword arg "isprivate" specifies a function used to
 
1876
    determine whether a name is private.  The default function is
 
1877
    treat all functions as public.  Optionally, "isprivate" can be
 
1878
    set to doctest.is_private to skip over functions marked as private
 
1879
    using the underscore naming convention; see its docs for details.
 
1880
 
 
1881
    Advanced tomfoolery:  testmod runs methods of a local instance of
 
1882
    class doctest.Tester, then merges the results into (or creates)
 
1883
    global Tester instance doctest.master.  Methods of doctest.master
 
1884
    can be called directly too, if you want to do something unusual.
 
1885
    Passing report=0 to testmod is especially useful then, to delay
 
1886
    displaying a summary.  Invoke doctest.master.summarize(verbose)
 
1887
    when you're done fiddling.
 
1888
    """
 
1889
    global master
 
1890
 
 
1891
    if isprivate is not None:
 
1892
        warnings.warn("the isprivate argument is deprecated; "
 
1893
                      "examine DocTestFinder.find() lists instead",
 
1894
                      DeprecationWarning)
 
1895
 
 
1896
    # If no module was given, then use __main__.
 
1897
    if m is None:
 
1898
        # DWA - m will still be None if this wasn't invoked from the command
 
1899
        # line, in which case the following TypeError is about as good an error
 
1900
        # as we should expect
 
1901
        m = sys.modules.get('__main__')
 
1902
 
 
1903
    # Check that we were actually given a module.
 
1904
    if not inspect.ismodule(m):
 
1905
        raise TypeError("testmod: module required; %r" % (m,))
 
1906
 
 
1907
    # If no name was given, then use the module's name.
 
1908
    if name is None:
 
1909
        name = m.__name__
 
1910
 
 
1911
    # Find, parse, and run all tests in the given module.
 
1912
    finder = DocTestFinder(_namefilter=isprivate, exclude_empty=exclude_empty)
 
1913
 
 
1914
    if raise_on_error:
 
1915
        runner = DebugRunner(verbose=verbose, optionflags=optionflags)
 
1916
    else:
 
1917
        runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
 
1918
 
 
1919
    for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
 
1920
        runner.run(test)
 
1921
 
 
1922
    if report:
 
1923
        runner.summarize()
 
1924
 
 
1925
    if master is None:
 
1926
        master = runner
 
1927
    else:
 
1928
        master.merge(runner)
 
1929
 
 
1930
    return runner.failures, runner.tries
 
1931
 
 
1932
def testfile(filename, module_relative=True, name=None, package=None,
 
1933
             globs=None, verbose=None, report=True, optionflags=0,
 
1934
             extraglobs=None, raise_on_error=False, parser=DocTestParser(),
 
1935
             encoding=None):
 
1936
    """
 
1937
    Test examples in the given file.  Return (#failures, #tests).
 
1938
 
 
1939
    Optional keyword arg "module_relative" specifies how filenames
 
1940
    should be interpreted:
 
1941
 
 
1942
      - If "module_relative" is True (the default), then "filename"
 
1943
         specifies a module-relative path.  By default, this path is
 
1944
         relative to the calling module's directory; but if the
 
1945
         "package" argument is specified, then it is relative to that
 
1946
         package.  To ensure os-independence, "filename" should use
 
1947
         "/" characters to separate path segments, and should not
 
1948
         be an absolute path (i.e., it may not begin with "/").
 
1949
 
 
1950
      - If "module_relative" is False, then "filename" specifies an
 
1951
        os-specific path.  The path may be absolute or relative (to
 
1952
        the current working directory).
 
1953
 
 
1954
    Optional keyword arg "name" gives the name of the test; by default
 
1955
    use the file's basename.
 
1956
 
 
1957
    Optional keyword argument "package" is a Python package or the
 
1958
    name of a Python package whose directory should be used as the
 
1959
    base directory for a module relative filename.  If no package is
 
1960
    specified, then the calling module's directory is used as the base
 
1961
    directory for module relative filenames.  It is an error to
 
1962
    specify "package" if "module_relative" is False.
 
1963
 
 
1964
    Optional keyword arg "globs" gives a dict to be used as the globals
 
1965
    when executing examples; by default, use {}.  A copy of this dict
 
1966
    is actually used for each docstring, so that each docstring's
 
1967
    examples start with a clean slate.
 
1968
 
 
1969
    Optional keyword arg "extraglobs" gives a dictionary that should be
 
1970
    merged into the globals that are used to execute examples.  By
 
1971
    default, no extra globals are used.
 
1972
 
 
1973
    Optional keyword arg "verbose" prints lots of stuff if true, prints
 
1974
    only failures if false; by default, it's true iff "-v" is in sys.argv.
 
1975
 
 
1976
    Optional keyword arg "report" prints a summary at the end when true,
 
1977
    else prints nothing at the end.  In verbose mode, the summary is
 
1978
    detailed, else very brief (in fact, empty if all tests passed).
 
1979
 
 
1980
    Optional keyword arg "optionflags" or's together module constants,
 
1981
    and defaults to 0.  Possible values (see the docs for details):
 
1982
 
 
1983
        DONT_ACCEPT_TRUE_FOR_1
 
1984
        DONT_ACCEPT_BLANKLINE
 
1985
        NORMALIZE_WHITESPACE
 
1986
        ELLIPSIS
 
1987
        IGNORE_EXCEPTION_DETAIL
 
1988
        REPORT_UDIFF
 
1989
        REPORT_CDIFF
 
1990
        REPORT_NDIFF
 
1991
        REPORT_ONLY_FIRST_FAILURE
 
1992
 
 
1993
    Optional keyword arg "raise_on_error" raises an exception on the
 
1994
    first unexpected exception or failure. This allows failures to be
 
1995
    post-mortem debugged.
 
1996
 
 
1997
    Optional keyword arg "parser" specifies a DocTestParser (or
 
1998
    subclass) that should be used to extract tests from the files.
 
1999
 
 
2000
    Optional keyword arg "encoding" specifies an encoding that should
 
2001
    be used to convert the file to unicode.
 
2002
 
 
2003
    Advanced tomfoolery:  testmod runs methods of a local instance of
 
2004
    class doctest.Tester, then merges the results into (or creates)
 
2005
    global Tester instance doctest.master.  Methods of doctest.master
 
2006
    can be called directly too, if you want to do something unusual.
 
2007
    Passing report=0 to testmod is especially useful then, to delay
 
2008
    displaying a summary.  Invoke doctest.master.summarize(verbose)
 
2009
    when you're done fiddling.
 
2010
    """
 
2011
    global master
 
2012
 
 
2013
    if package and not module_relative:
 
2014
        raise ValueError("Package may only be specified for module-"
 
2015
                         "relative paths.")
 
2016
 
 
2017
    # Relativize the path
 
2018
    if module_relative:
 
2019
        package = _normalize_module(package)
 
2020
        filename = _module_relative_path(package, filename)
 
2021
 
 
2022
    # If no name was given, then use the file's name.
 
2023
    if name is None:
 
2024
        name = os.path.basename(filename)
 
2025
 
 
2026
    # Assemble the globals.
 
2027
    if globs is None:
 
2028
        globs = {}
 
2029
    else:
 
2030
        globs = globs.copy()
 
2031
    if extraglobs is not None:
 
2032
        globs.update(extraglobs)
 
2033
 
 
2034
    if raise_on_error:
 
2035
        runner = DebugRunner(verbose=verbose, optionflags=optionflags)
 
2036
    else:
 
2037
        runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
 
2038
 
 
2039
    # Read the file, convert it to a test, and run it.
 
2040
    s = open(filename, 'U').read()
 
2041
    if encoding is None:
 
2042
        encoding = pep263_encoding(s)
 
2043
    if encoding is not None:
 
2044
        s = s.decode(encoding)
 
2045
    test = parser.get_doctest(s, globs, name, filename, 0)
 
2046
    runner.run(test)
 
2047
 
 
2048
    if report:
 
2049
        runner.summarize()
 
2050
 
 
2051
    if master is None:
 
2052
        master = runner
 
2053
    else:
 
2054
        master.merge(runner)
 
2055
 
 
2056
    return runner.failures, runner.tries
 
2057
 
 
2058
pep263_re_search = re.compile("coding[:=]\s*([-\w.]+)").search
 
2059
def pep263_encoding(s):
 
2060
    """Try to find the encoding of a string by looking for a pep263 coding.
 
2061
    """
 
2062
    for line in s.split('\n')[:2]:
 
2063
        r = pep263_re_search(line)
 
2064
        if r:
 
2065
            return r.group(1)
 
2066
 
 
2067
 
 
2068
 
 
2069
def run_docstring_examples(f, globs, verbose=False, name="NoName",
 
2070
                           compileflags=None, optionflags=0):
 
2071
    """
 
2072
    Test examples in the given object's docstring (`f`), using `globs`
 
2073
    as globals.  Optional argument `name` is used in failure messages.
 
2074
    If the optional argument `verbose` is true, then generate output
 
2075
    even if there are no failures.
 
2076
 
 
2077
    `compileflags` gives the set of flags that should be used by the
 
2078
    Python compiler when running the examples.  If not specified, then
 
2079
    it will default to the set of future-import flags that apply to
 
2080
    `globs`.
 
2081
 
 
2082
    Optional keyword arg `optionflags` specifies options for the
 
2083
    testing and output.  See the documentation for `testmod` for more
 
2084
    information.
 
2085
    """
 
2086
    # Find, parse, and run all tests in the given module.
 
2087
    finder = DocTestFinder(verbose=verbose, recurse=False)
 
2088
    runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
 
2089
    for test in finder.find(f, name, globs=globs):
 
2090
        runner.run(test, compileflags=compileflags)
 
2091
 
 
2092
######################################################################
 
2093
## 7. Tester
 
2094
######################################################################
 
2095
# This is provided only for backwards compatibility.  It's not
 
2096
# actually used in any way.
 
2097
 
 
2098
class Tester:
 
2099
    def __init__(self, mod=None, globs=None, verbose=None,
 
2100
                 isprivate=None, optionflags=0):
 
2101
 
 
2102
        warnings.warn("class Tester is deprecated; "
 
2103
                      "use class doctest.DocTestRunner instead",
 
2104
                      DeprecationWarning, stacklevel=2)
 
2105
        if mod is None and globs is None:
 
2106
            raise TypeError("Tester.__init__: must specify mod or globs")
 
2107
        if mod is not None and not inspect.ismodule(mod):
 
2108
            raise TypeError("Tester.__init__: mod must be a module; %r" %
 
2109
                            (mod,))
 
2110
        if globs is None:
 
2111
            globs = mod.__dict__
 
2112
        self.globs = globs
 
2113
 
 
2114
        self.verbose = verbose
 
2115
        self.isprivate = isprivate
 
2116
        self.optionflags = optionflags
 
2117
        self.testfinder = DocTestFinder(_namefilter=isprivate)
 
2118
        self.testrunner = DocTestRunner(verbose=verbose,
 
2119
                                        optionflags=optionflags)
 
2120
 
 
2121
    def runstring(self, s, name):
 
2122
        test = DocTestParser().get_doctest(s, self.globs, name, None, None,
 
2123
                                           self.optionflags)
 
2124
        if self.verbose:
 
2125
            print "Running string", name
 
2126
        (f,t) = self.testrunner.run(test)
 
2127
        if self.verbose:
 
2128
            print f, "of", t, "examples failed in string", name
 
2129
        return (f,t)
 
2130
 
 
2131
    def rundoc(self, object, name=None, module=None):
 
2132
        f = t = 0
 
2133
        tests = self.testfinder.find(object, name, module=module,
 
2134
                                     globs=self.globs)
 
2135
        for test in tests:
 
2136
            (f2, t2) = self.testrunner.run(test)
 
2137
            (f,t) = (f+f2, t+t2)
 
2138
        return (f,t)
 
2139
 
 
2140
    def rundict(self, d, name, module=None):
 
2141
        import new
 
2142
        m = new.module(name)
 
2143
        m.__dict__.update(d)
 
2144
        if module is None:
 
2145
            module = False
 
2146
        return self.rundoc(m, name, module)
 
2147
 
 
2148
    def run__test__(self, d, name):
 
2149
        import new
 
2150
        m = new.module(name)
 
2151
        m.__test__ = d
 
2152
        return self.rundoc(m, name)
 
2153
 
 
2154
    def summarize(self, verbose=None):
 
2155
        return self.testrunner.summarize(verbose)
 
2156
 
 
2157
    def merge(self, other):
 
2158
        self.testrunner.merge(other.testrunner)
 
2159
 
 
2160
######################################################################
 
2161
## 8. Unittest Support
 
2162
######################################################################
 
2163
 
 
2164
from doctest import set_unittest_reportflags
 
2165
 
 
2166
_para_re = re.compile(r'\s*\n\s*\n\s*')
 
2167
def _unittest_count(docstring):
 
2168
    words = 0
 
2169
    count = 0
 
2170
    for p in _para_re.split(docstring):
 
2171
        p = p.strip()
 
2172
        if not p:
 
2173
            continue
 
2174
        if p.startswith('>>> '):
 
2175
            if words:
 
2176
                count += 1
 
2177
                words = 0
 
2178
        else:
 
2179
            words = 1
 
2180
 
 
2181
    return count or 1
 
2182
 
 
2183
 
 
2184
class DocTestCase(unittest.TestCase):
 
2185
 
 
2186
    def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
 
2187
                 checker=None):
 
2188
 
 
2189
        unittest.TestCase.__init__(self)
 
2190
        self._dt_optionflags = optionflags
 
2191
        self._dt_checker = checker
 
2192
        self._dt_test = test
 
2193
        self._dt_globs = test.globs.copy()
 
2194
        self._dt_setUp = setUp
 
2195
        self._dt_tearDown = tearDown
 
2196
 
 
2197
        self._dt_count = _unittest_count(test.docstring)
 
2198
 
 
2199
    def countTestCases(self):
 
2200
        return self._dt_count
 
2201
 
 
2202
    def setUp(self):
 
2203
        test = self._dt_test
 
2204
 
 
2205
        if self._dt_setUp is not None:
 
2206
            self._dt_setUp(test)
 
2207
 
 
2208
    def tearDown(self):
 
2209
        test = self._dt_test
 
2210
 
 
2211
        if self._dt_tearDown is not None:
 
2212
            self._dt_tearDown(test)
 
2213
 
 
2214
        # restore the original globs
 
2215
        test.globs.clear()
 
2216
        test.globs.update(self._dt_globs)
 
2217
 
 
2218
    failureException = DocTestFailureException
 
2219
 
 
2220
    def runTest(self):
 
2221
        test = self._dt_test
 
2222
        old = sys.stdout
 
2223
        new = StringIO()
 
2224
        optionflags = self._dt_optionflags
 
2225
 
 
2226
        if not (optionflags & REPORTING_FLAGS):
 
2227
            # The option flags don't include any reporting flags,
 
2228
            # so add the default reporting flags
 
2229
            optionflags |= doctest._unittest_reportflags
 
2230
 
 
2231
        if doctest._unittest_reportflags & REPORT_ONLY_FIRST_FAILURE:
 
2232
            optionflags |= REPORT_ONLY_FIRST_FAILURE
 
2233
 
 
2234
        runner = DocTestRunner(optionflags=optionflags,
 
2235
                               checker=self._dt_checker, verbose=False)
 
2236
        def write(value):
 
2237
            if isinstance(value, unicode):
 
2238
                value = value.encode('utf8')
 
2239
            new.write(value)
 
2240
 
 
2241
        try:
 
2242
            runner.DIVIDER = "-"*70
 
2243
            failures, tries = runner.run(
 
2244
                test, out=write, clear_globs=False)
 
2245
        finally:
 
2246
            sys.stdout = old
 
2247
 
 
2248
        if failures:
 
2249
            raise self.failureException(self.format_failure(new.getvalue()))
 
2250
 
 
2251
    def format_failure(self, err):
 
2252
        test = self._dt_test
 
2253
        if test.lineno is None:
 
2254
            lineno = 'unknown line number'
 
2255
        else:
 
2256
            lineno = '%s' % test.lineno
 
2257
        lname = '.'.join(test.name.split('.')[-1:])
 
2258
        return ('Failed doctest test for %s\n'
 
2259
                '  File "%s", line %s, in %s\n\n%s'
 
2260
                % (test.name, test.filename, lineno, lname, err)
 
2261
                )
 
2262
 
 
2263
    def debug(self):
 
2264
        r"""Run the test case without results and without catching exceptions
 
2265
 
 
2266
           The unit test framework includes a debug method on test cases
 
2267
           and test suites to support post-mortem debugging.  The test code
 
2268
           is run in such a way that errors are not caught.  This way a
 
2269
           caller can catch the errors and initiate post-mortem debugging.
 
2270
 
 
2271
           The DocTestCase provides a debug method that raises
 
2272
           UnexpectedException errors if there is an unexepcted
 
2273
           exception:
 
2274
 
 
2275
             >>> test = DocTestParser().get_doctest('>>> raise KeyError\n42',
 
2276
             ...                {}, 'foo', 'foo.py', 0)
 
2277
             >>> case = DocTestCase(test)
 
2278
             >>> try:
 
2279
             ...     case.debug()
 
2280
             ... except UnexpectedException, failure:
 
2281
             ...     pass
 
2282
 
 
2283
           The UnexpectedException contains the test, the example, and
 
2284
           the original exception:
 
2285
 
 
2286
             >>> failure.test is test
 
2287
             True
 
2288
 
 
2289
             >>> failure.example.want
 
2290
             '42\n'
 
2291
 
 
2292
             >>> exc_info = failure.exc_info
 
2293
             >>> raise exc_info[0], exc_info[1], exc_info[2]
 
2294
             Traceback (most recent call last):
 
2295
             ...
 
2296
             KeyError
 
2297
 
 
2298
           If the output doesn't match, then a DocTestFailure is raised:
 
2299
 
 
2300
             >>> test = DocTestParser().get_doctest('''
 
2301
             ...      >>> x = 1
 
2302
             ...      >>> x
 
2303
             ...      2
 
2304
             ...      ''', {}, 'foo', 'foo.py', 0)
 
2305
             >>> case = DocTestCase(test)
 
2306
 
 
2307
             >>> try:
 
2308
             ...    case.debug()
 
2309
             ... except DocTestFailure, failure:
 
2310
             ...    pass
 
2311
 
 
2312
           DocTestFailure objects provide access to the test:
 
2313
 
 
2314
             >>> failure.test is test
 
2315
             True
 
2316
 
 
2317
           As well as to the example:
 
2318
 
 
2319
             >>> failure.example.want
 
2320
             '2\n'
 
2321
 
 
2322
           and the actual output:
 
2323
 
 
2324
             >>> failure.got
 
2325
             '1\n'
 
2326
 
 
2327
           """
 
2328
 
 
2329
        self.setUp()
 
2330
        runner = DebugRunner(optionflags=self._dt_optionflags,
 
2331
                             checker=self._dt_checker, verbose=False)
 
2332
        runner.run(self._dt_test, clear_globs=False)
 
2333
        self.tearDown()
 
2334
 
 
2335
    def id(self):
 
2336
        return self._dt_test.name
 
2337
 
 
2338
    def __repr__(self):
 
2339
        name = self._dt_test.name.split('.')
 
2340
        return "%s (%s)" % (name[-1], '.'.join(name[:-1]))
 
2341
 
 
2342
    __str__ = __repr__
 
2343
 
 
2344
    def shortDescription(self):
 
2345
        return "Doctest: " + self._dt_test.name
 
2346
 
 
2347
def DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None,
 
2348
                 **options):
 
2349
    """
 
2350
    Convert doctest tests for a module to a unittest test suite.
 
2351
 
 
2352
    This converts each documentation string in a module that
 
2353
    contains doctest tests to a unittest test case.  If any of the
 
2354
    tests in a doc string fail, then the test case fails.  An exception
 
2355
    is raised showing the name of the file containing the test and a
 
2356
    (sometimes approximate) line number.
 
2357
 
 
2358
    The `module` argument provides the module to be tested.  The argument
 
2359
    can be either a module or a module name.
 
2360
 
 
2361
    If no argument is given, the calling module is used.
 
2362
 
 
2363
    A number of options may be provided as keyword arguments:
 
2364
 
 
2365
    setUp
 
2366
      A set-up function.  This is called before running the
 
2367
      tests in each file. The setUp function will be passed a DocTest
 
2368
      object.  The setUp function can access the test globals as the
 
2369
      globs attribute of the test passed.
 
2370
 
 
2371
    tearDown
 
2372
      A tear-down function.  This is called after running the
 
2373
      tests in each file.  The tearDown function will be passed a DocTest
 
2374
      object.  The tearDown function can access the test globals as the
 
2375
      globs attribute of the test passed.
 
2376
 
 
2377
    globs
 
2378
      A dictionary containing initial global variables for the tests.
 
2379
 
 
2380
    optionflags
 
2381
       A set of doctest option flags expressed as an integer.
 
2382
    """
 
2383
 
 
2384
    if test_finder is None:
 
2385
        test_finder = DocTestFinder()
 
2386
 
 
2387
    module = _normalize_module(module)
 
2388
    tests = test_finder.find(module, globs=globs, extraglobs=extraglobs,
 
2389
                             optionflags=options.get('optionflags', 0))
 
2390
    if globs is None:
 
2391
        globs = module.__dict__
 
2392
    if not tests:
 
2393
        # Why do we want to do this? Because it reveals a bug that might
 
2394
        # otherwise be hidden.
 
2395
        raise ValueError(module, "has no tests")
 
2396
 
 
2397
    tests.sort()
 
2398
    suite = unittest.TestSuite()
 
2399
    for test in tests:
 
2400
        if len(test.examples) == 0:
 
2401
            continue
 
2402
        if not test.filename:
 
2403
            filename = module.__file__
 
2404
            if filename[-4:] in (".pyc", ".pyo"):
 
2405
                filename = filename[:-1]
 
2406
            test.filename = filename
 
2407
        suite.addTest(DocTestCase(test, **options))
 
2408
 
 
2409
    return suite
 
2410
 
 
2411
class DocFileCase(DocTestCase):
 
2412
 
 
2413
    def id(self):
 
2414
        return '_'.join(self._dt_test.name.split('.'))
 
2415
 
 
2416
    def __repr__(self):
 
2417
        return self._dt_test.filename
 
2418
    __str__ = __repr__
 
2419
 
 
2420
    def format_failure(self, err):
 
2421
        return ('Failed doctest test for %s\n  File "%s", line 0\n\n%s'
 
2422
                % (self._dt_test.name, self._dt_test.filename, err)
 
2423
                )
 
2424
 
 
2425
def DocFileTest(path, module_relative=True, package=None,
 
2426
                globs=None, parser=DocTestParser(),
 
2427
                encoding=None, **options):
 
2428
    if globs is None:
 
2429
        globs = {}
 
2430
    else:
 
2431
        globs = globs.copy()
 
2432
 
 
2433
    if package and not module_relative:
 
2434
        raise ValueError("Package may only be specified for module-"
 
2435
                         "relative paths.")
 
2436
 
 
2437
    # Relativize the path.
 
2438
    if module_relative:
 
2439
        package = _normalize_module(package)
 
2440
        path = _module_relative_path(package, path)
 
2441
    if "__file__" not in globs:
 
2442
        globs["__file__"] = path
 
2443
 
 
2444
    # Find the file and read it.
 
2445
    name = os.path.basename(path)
 
2446
    doc = open(path, 'U').read()
 
2447
 
 
2448
    # If an encoding is specified, use it to convert the file to unicode
 
2449
    if encoding is None:
 
2450
        encoding = pep263_encoding(doc)
 
2451
    if encoding is not None:
 
2452
        doc = doc.decode(encoding)
 
2453
 
 
2454
    optionflags = options.get('optionflags', 0)
 
2455
    # Convert it to a test, and wrap it in a DocFileCase.
 
2456
    test = parser.get_doctest(doc, globs, name, path, 0, optionflags)
 
2457
    return DocFileCase(test, **options)
 
2458
 
 
2459
def DocFileSuite(*paths, **kw):
 
2460
    """A unittest suite for one or more doctest files.
 
2461
 
 
2462
    The path to each doctest file is given as a string; the
 
2463
    interpretation of that string depends on the keyword argument
 
2464
    "module_relative".
 
2465
 
 
2466
    A number of options may be provided as keyword arguments:
 
2467
 
 
2468
    module_relative
 
2469
      If "module_relative" is True, then the given file paths are
 
2470
      interpreted as os-independent module-relative paths.  By
 
2471
      default, these paths are relative to the calling module's
 
2472
      directory; but if the "package" argument is specified, then
 
2473
      they are relative to that package.  To ensure os-independence,
 
2474
      "filename" should use "/" characters to separate path
 
2475
      segments, and may not be an absolute path (i.e., it may not
 
2476
      begin with "/").
 
2477
 
 
2478
      If "module_relative" is False, then the given file paths are
 
2479
      interpreted as os-specific paths.  These paths may be absolute
 
2480
      or relative (to the current working directory).
 
2481
 
 
2482
    package
 
2483
      A Python package or the name of a Python package whose directory
 
2484
      should be used as the base directory for module relative paths.
 
2485
      If "package" is not specified, then the calling module's
 
2486
      directory is used as the base directory for module relative
 
2487
      filenames.  It is an error to specify "package" if
 
2488
      "module_relative" is False.
 
2489
 
 
2490
    setUp
 
2491
      A set-up function.  This is called before running the
 
2492
      tests in each file. The setUp function will be passed a DocTest
 
2493
      object.  The setUp function can access the test globals as the
 
2494
      globs attribute of the test passed.
 
2495
 
 
2496
    tearDown
 
2497
      A tear-down function.  This is called after running the
 
2498
      tests in each file.  The tearDown function will be passed a DocTest
 
2499
      object.  The tearDown function can access the test globals as the
 
2500
      globs attribute of the test passed.
 
2501
 
 
2502
    globs
 
2503
      A dictionary containing initial global variables for the tests.
 
2504
 
 
2505
    optionflags
 
2506
      A set of doctest option flags expressed as an integer.
 
2507
 
 
2508
    parser
 
2509
      A DocTestParser (or subclass) that should be used to extract
 
2510
      tests from the files.
 
2511
 
 
2512
    encoding
 
2513
      An encoding that will be used to convert the files to unicode.
 
2514
    """
 
2515
    suite = unittest.TestSuite()
 
2516
 
 
2517
    # We do this here so that _normalize_module is called at the right
 
2518
    # level.  If it were called in DocFileTest, then this function
 
2519
    # would be the caller and we might guess the package incorrectly.
 
2520
    if kw.get('module_relative', True):
 
2521
        kw['package'] = _normalize_module(kw.get('package'))
 
2522
 
 
2523
    for path in paths:
 
2524
        suite.addTest(DocFileTest(path, **kw))
 
2525
 
 
2526
    return suite
 
2527
 
 
2528
######################################################################
 
2529
## 9. Debugging Support
 
2530
######################################################################
 
2531
 
 
2532
def script_from_examples(s):
 
2533
    r"""Extract script from text with examples.
 
2534
 
 
2535
       Converts text with examples to a Python script.  Example input is
 
2536
       converted to regular code.  Example output and all other words
 
2537
       are converted to comments:
 
2538
 
 
2539
       >>> text = '''
 
2540
       ...       Here are examples of simple math.
 
2541
       ...
 
2542
       ...           Python has super accurate integer addition
 
2543
       ...
 
2544
       ...           >>> 2 + 2
 
2545
       ...           5
 
2546
       ...
 
2547
       ...           And very friendly error messages:
 
2548
       ...
 
2549
       ...           >>> 1/0
 
2550
       ...           To Infinity
 
2551
       ...           And
 
2552
       ...           Beyond
 
2553
       ...
 
2554
       ...           You can use logic if you want:
 
2555
       ...
 
2556
       ...           >>> if 0:
 
2557
       ...           ...    blah
 
2558
       ...           ...    blah
 
2559
       ...           ...
 
2560
       ...
 
2561
       ...           Ho hum
 
2562
       ...           '''
 
2563
 
 
2564
       >>> print script_from_examples(text)
 
2565
       # Here are examples of simple math.
 
2566
       #
 
2567
       #     Python has super accurate integer addition
 
2568
       #
 
2569
       2 + 2
 
2570
       # Expected:
 
2571
       ## 5
 
2572
       #
 
2573
       #     And very friendly error messages:
 
2574
       #
 
2575
       1/0
 
2576
       # Expected:
 
2577
       ## To Infinity
 
2578
       ## And
 
2579
       ## Beyond
 
2580
       #
 
2581
       #     You can use logic if you want:
 
2582
       #
 
2583
       if 0:
 
2584
          blah
 
2585
          blah
 
2586
       #
 
2587
       #     Ho hum
 
2588
       """
 
2589
    output = []
 
2590
    for piece in DocTestParser().parse(s):
 
2591
        if isinstance(piece, Example):
 
2592
            # Add the example's source code (strip trailing NL)
 
2593
            output.append(piece.source[:-1])
 
2594
            # Add the expected output:
 
2595
            want = piece.want
 
2596
            if want:
 
2597
                output.append('# Expected:')
 
2598
                output += ['## '+l for l in want.split('\n')[:-1]]
 
2599
        else:
 
2600
            # Add non-example text.
 
2601
            output += [_comment_line(l)
 
2602
                       for l in piece.split('\n')[:-1]]
 
2603
 
 
2604
    # Trim junk on both ends.
 
2605
    while output and output[-1] == '#':
 
2606
        output.pop()
 
2607
    while output and output[0] == '#':
 
2608
        output.pop(0)
 
2609
    # Combine the output, and return it.
 
2610
    return '\n'.join(output)
 
2611
 
 
2612
def testsource(module, name):
 
2613
    """Extract the test sources from a doctest docstring as a script.
 
2614
 
 
2615
    Provide the module (or dotted name of the module) containing the
 
2616
    test to be debugged and the name (within the module) of the object
 
2617
    with the doc string with tests to be debugged.
 
2618
    """
 
2619
    module = _normalize_module(module)
 
2620
    tests = DocTestFinder().find(module)
 
2621
    test = [t for t in tests if t.name == name]
 
2622
    if not test:
 
2623
        raise ValueError(name, "not found in tests")
 
2624
    test = test[0]
 
2625
    testsrc = script_from_examples(test.docstring)
 
2626
    return testsrc
 
2627
 
 
2628
def debug_src(src, pm=False, globs=None):
 
2629
    """Debug a single doctest docstring, in argument `src`'"""
 
2630
    testsrc = script_from_examples(src)
 
2631
    debug_script(testsrc, pm, globs)
 
2632
 
 
2633
def debug_script(src, pm=False, globs=None):
 
2634
    "Debug a test script.  `src` is the script, as a string."
 
2635
    import pdb
 
2636
 
 
2637
    # Note that tempfile.NameTemporaryFile() cannot be used.  As the
 
2638
    # docs say, a file so created cannot be opened by name a second time
 
2639
    # on modern Windows boxes, and execfile() needs to open it.
 
2640
    srcfilename = tempfile.mktemp(".py", "doctestdebug")
 
2641
    f = open(srcfilename, 'w')
 
2642
    f.write(src)
 
2643
    f.close()
 
2644
 
 
2645
    try:
 
2646
        if globs:
 
2647
            globs = globs.copy()
 
2648
        else:
 
2649
            globs = {}
 
2650
 
 
2651
        if pm:
 
2652
            try:
 
2653
                execfile(srcfilename, globs, globs)
 
2654
            except:
 
2655
                print sys.exc_info()[1]
 
2656
                pdb.post_mortem(sys.exc_info()[2])
 
2657
        else:
 
2658
            # Note that %r is vital here.  '%s' instead can, e.g., cause
 
2659
            # backslashes to get treated as metacharacters on Windows.
 
2660
            pdb.run("execfile(%r)" % srcfilename, globs, globs)
 
2661
 
 
2662
    finally:
 
2663
        os.remove(srcfilename)
 
2664
 
 
2665
def debug(module, name, pm=False):
 
2666
    """Debug a single doctest docstring.
 
2667
 
 
2668
    Provide the module (or dotted name of the module) containing the
 
2669
    test to be debugged and the name (within the module) of the object
 
2670
    with the docstring with tests to be debugged.
 
2671
    """
 
2672
    module = _normalize_module(module)
 
2673
    testsrc = testsource(module, name)
 
2674
    debug_script(testsrc, pm, module.__dict__)
 
2675
 
 
2676
######################################################################
 
2677
## 10. Example Usage
 
2678
######################################################################
 
2679
class _TestClass:
 
2680
    """
 
2681
    A pointless class, for sanity-checking of docstring testing.
 
2682
 
 
2683
    Methods:
 
2684
        square()
 
2685
        get()
 
2686
 
 
2687
    >>> _TestClass(13).get() + _TestClass(-12).get()
 
2688
    1
 
2689
    >>> hex(_TestClass(13).square().get())
 
2690
    '0xa9'
 
2691
    """
 
2692
 
 
2693
    def __init__(self, val):
 
2694
        """val -> _TestClass object with associated value val.
 
2695
 
 
2696
        >>> t = _TestClass(123)
 
2697
        >>> print t.get()
 
2698
        123
 
2699
        """
 
2700
 
 
2701
        self.val = val
 
2702
 
 
2703
    def square(self):
 
2704
        """square() -> square TestClass's associated value
 
2705
 
 
2706
        >>> _TestClass(13).square().get()
 
2707
        169
 
2708
        """
 
2709
 
 
2710
        self.val = self.val ** 2
 
2711
        return self
 
2712
 
 
2713
    def get(self):
 
2714
        """get() -> return TestClass's associated value.
 
2715
 
 
2716
        >>> x = _TestClass(-42)
 
2717
        >>> print x.get()
 
2718
        -42
 
2719
        """
 
2720
 
 
2721
        return self.val
 
2722
 
 
2723
__test__ = {"_TestClass": _TestClass,
 
2724
            "string": r"""
 
2725
                      Example of a string object, searched as-is.
 
2726
                      >>> x = 1; y = 2
 
2727
                      >>> x + y, x * y
 
2728
                      (3, 2)
 
2729
                      """,
 
2730
 
 
2731
            "bool-int equivalence": r"""
 
2732
                                    In 2.2, boolean expressions displayed
 
2733
                                    0 or 1.  By default, we still accept
 
2734
                                    them.  This can be disabled by passing
 
2735
                                    DONT_ACCEPT_TRUE_FOR_1 to the new
 
2736
                                    optionflags argument.
 
2737
                                    >>> 4 == 4
 
2738
                                    1
 
2739
                                    >>> 4 == 4
 
2740
                                    True
 
2741
                                    >>> 4 > 4
 
2742
                                    0
 
2743
                                    >>> 4 > 4
 
2744
                                    False
 
2745
                                    """,
 
2746
 
 
2747
            "blank lines": r"""
 
2748
                Blank lines can be marked with <BLANKLINE>:
 
2749
                    >>> print 'foo\n\nbar\n'
 
2750
                    foo
 
2751
                    <BLANKLINE>
 
2752
                    bar
 
2753
                    <BLANKLINE>
 
2754
            """,
 
2755
 
 
2756
            "ellipsis": r"""
 
2757
                If the ellipsis flag is used, then '...' can be used to
 
2758
                elide substrings in the desired output:
 
2759
                    >>> print range(1000) #doctest: +ELLIPSIS
 
2760
                    [0, 1, 2, ..., 999]
 
2761
            """,
 
2762
 
 
2763
            "whitespace normalization": r"""
 
2764
                If the whitespace normalization flag is used, then
 
2765
                differences in whitespace are ignored.
 
2766
                    >>> print range(30) #doctest: +NORMALIZE_WHITESPACE
 
2767
                    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
 
2768
                     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
 
2769
                     27, 28, 29]
 
2770
            """,
 
2771
           }
 
2772
 
 
2773
def _test_footnotes():
 
2774
    '''
 
2775
    Footnotes
 
2776
    =========
 
2777
 
 
2778
    If the INTERPRET_FOOTNOTES flag is passed as part of optionflags, then
 
2779
    footnotes will be looked up and their code injected at each point of
 
2780
    reference.  For example:
 
2781
 
 
2782
        >>> counter = 0
 
2783
 
 
2784
    Here is some text that references a footnote [1]_
 
2785
 
 
2786
        >>> counter
 
2787
        1
 
2788
 
 
2789
    .. [1] and here we increment ``counter``
 
2790
        >>> counter += 1
 
2791
 
 
2792
    Footnotes can also be referenced after they are defined: [1]_
 
2793
 
 
2794
        >>> counter
 
2795
        2
 
2796
 
 
2797
    Footnotes can also be "citations", which just means that the value in
 
2798
    the brackets is alphanumeric: [citation]_
 
2799
 
 
2800
        >>> print from_citation
 
2801
        hi
 
2802
 
 
2803
    .. [citation] this is a citation.
 
2804
        >>> from_citation = 'hi'
 
2805
 
 
2806
    Footnotes can contain more than one example: [multi example]_
 
2807
 
 
2808
        >>> print one
 
2809
        1
 
2810
 
 
2811
        >>> print two
 
2812
        2
 
2813
 
 
2814
        >>> print three
 
2815
        3
 
2816
 
 
2817
    .. [multi example] Here's a footnote with multiple examples:
 
2818
 
 
2819
        >>> one = 1
 
2820
 
 
2821
        and now another (note indentation to make this part of the footnote):
 
2822
 
 
2823
        >>> two = 2
 
2824
 
 
2825
        and a third:
 
2826
 
 
2827
        >>> three = 3
 
2828
 
 
2829
 
 
2830
    More than one footnote can be referenced at a time [1]_ [2]_
 
2831
 
 
2832
        >>> counter
 
2833
        6
 
2834
 
 
2835
    .. [2] let's multiply ``counter`` by two
 
2836
        >>> counter *= 2
 
2837
 
 
2838
 
 
2839
    Parsing Details
 
2840
    ---------------
 
2841
 
 
2842
    If the INTERPRET_FOOTNOTES optionflag isn't set, footnotes are ignored.
 
2843
 
 
2844
    >>> doctest = """
 
2845
    ... This is a doctest. [#1]_
 
2846
    ...
 
2847
    ...     >>> print var
 
2848
    ...
 
2849
    ... .. [#1] a footnote
 
2850
    ...     Here we set up the variable
 
2851
    ...
 
2852
    ...     >>> var = 1
 
2853
    ... """
 
2854
 
 
2855
    >>> print_structure(doctest)
 
2856
    Prose| This is a doctest. [#1]_
 
2857
    Code | print var
 
2858
    Prose| .. [#1] a footnote
 
2859
    Code | var = 1
 
2860
    Prose|
 
2861
 
 
2862
    If INTERPRET_FOOTNOTES is set, footnotes are also copied to the point at
 
2863
    which they are referenced.
 
2864
 
 
2865
    >>> print_structure(doctest, optionflags=INTERPRET_FOOTNOTES)
 
2866
    Prose| This is a doctest. [#1]_
 
2867
    Code | var = 1
 
2868
    Prose|
 
2869
    Code | print var
 
2870
    Prose| .. [#1] a footnote
 
2871
    Prose|
 
2872
 
 
2873
    >>> print_structure("""
 
2874
    ... Footnotes can have code that starts with no prose. [#quick code]_
 
2875
    ...
 
2876
    ... .. [#quick code]
 
2877
    ...     >>> print 'this is some code'
 
2878
    ...     this is some code
 
2879
    ... """, optionflags=INTERPRET_FOOTNOTES)
 
2880
    Prose| Footnotes can have code that starts with no prose. [#quick code]_
 
2881
    Code | print 'this is some code'
 
2882
    Prose|
 
2883
    Prose|
 
2884
 
 
2885
    >>> print_structure("""
 
2886
    ... Footnotes can be back-to-back [#first]_ [#second]_
 
2887
    ... .. [#first]
 
2888
    ... .. [#second]
 
2889
    ...     >>> 1+1
 
2890
    ...     2
 
2891
    ... """, optionflags=INTERPRET_FOOTNOTES)
 
2892
    Prose| Footnotes can be back-to-back [#first]_ [#second]_
 
2893
    Prose| Footnotes can be back-to-back [#first]_ [#second]_
 
2894
    Code | 1+1
 
2895
    Prose|
 
2896
    Prose|
 
2897
 
 
2898
    >>> print_structure("""
 
2899
    ... .. [#no code] Footnotes can also be defined with no code.
 
2900
    ... """, optionflags=INTERPRET_FOOTNOTES)
 
2901
    Prose| .. [#no code] Footnotes can also be defined with no code.
 
2902
 
 
2903
    If there are multiple footnotes with no code, then one with code, they are
 
2904
    parsed correctly.
 
2905
 
 
2906
    >>> print_structure("""
 
2907
    ... I'd like some code to go here [#some code]_
 
2908
    ... .. [#no code 1] Footnotes can also be defined with no code.
 
2909
    ... .. [#no code 2] Footnotes can also be defined with no code.
 
2910
    ... .. [#no code 3] Footnotes can also be defined with no code.
 
2911
    ... .. [#some code]
 
2912
    ...     >>> print 'hi'
 
2913
    ...     hi
 
2914
    ... """, optionflags=INTERPRET_FOOTNOTES)
 
2915
    Prose| I'd like some code to go here [#some code]_
 
2916
    Code | print 'hi'
 
2917
    Prose|
 
2918
    Prose|
 
2919
 
 
2920
    The non-autonumbered flavor of labels works too.
 
2921
 
 
2922
    >>> print_structure("""
 
2923
    ... Here is some text. [foo]_
 
2924
    ... .. [foo]
 
2925
    ...     >>> print 'hi'
 
2926
    ...     hi
 
2927
    ... """, optionflags=INTERPRET_FOOTNOTES)
 
2928
    Prose| Here is some text. [foo]_
 
2929
    Code | print 'hi'
 
2930
    Prose|
 
2931
    Prose|
 
2932
    '''
 
2933
 
 
2934
 
 
2935
def print_structure(doctest, optionflags=0):
 
2936
    def preview(s):
 
2937
        first_line = s.strip().split('\n')[0]
 
2938
        MAX_LENGTH = 70
 
2939
        if len(first_line) <= MAX_LENGTH:
 
2940
            return first_line
 
2941
 
 
2942
        return '%s...' % first_line[:MAX_LENGTH].strip()
 
2943
 
 
2944
    parser = DocTestParser()
 
2945
    for x in parser.parse(doctest, optionflags=optionflags):
 
2946
        if isinstance(x, Example):
 
2947
            result = 'Code | ' + preview(x.source)
 
2948
        else:
 
2949
            result = 'Prose| ' + preview(x)
 
2950
 
 
2951
        print result.strip()
 
2952
 
 
2953
 
 
2954
def _test():
 
2955
    r = unittest.TextTestRunner()
 
2956
    r.run(DocTestSuite(optionflags=INTERPRET_FOOTNOTES))
 
2957
 
 
2958
if __name__ == "__main__":
 
2959
    _test()
 
2960
 
 
2961
# TODO:
 
2962
# - make tracebacks show where the footnote was referenced
 
2963
# - teach script_from_examples and testsource about INTERPRET_FOOTNOTES
 
2964
# - update comments (including docstring for testfile)