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