Home | History | Annotate | Download | only in test
      1 # -*- coding: utf-8 -*-
      2 """
      3 Test script for doctest.
      4 """
      5 
      6 import sys
      7 from test import test_support
      8 import doctest
      9 
     10 # NOTE: There are some additional tests relating to interaction with
     11 #       zipimport in the test_zipimport_support test module.
     12 
     13 ######################################################################
     14 ## Sample Objects (used by test cases)
     15 ######################################################################
     16 
     17 def sample_func(v):
     18     """
     19     Blah blah
     20 
     21     >>> print sample_func(22)
     22     44
     23 
     24     Yee ha!
     25     """
     26     return v+v
     27 
     28 class SampleClass:
     29     """
     30     >>> print 1
     31     1
     32 
     33     >>> # comments get ignored.  so are empty PS1 and PS2 prompts:
     34     >>>
     35     ...
     36 
     37     Multiline example:
     38     >>> sc = SampleClass(3)
     39     >>> for i in range(10):
     40     ...     sc = sc.double()
     41     ...     print sc.get(),
     42     6 12 24 48 96 192 384 768 1536 3072
     43     """
     44     def __init__(self, val):
     45         """
     46         >>> print SampleClass(12).get()
     47         12
     48         """
     49         self.val = val
     50 
     51     def double(self):
     52         """
     53         >>> print SampleClass(12).double().get()
     54         24
     55         """
     56         return SampleClass(self.val + self.val)
     57 
     58     def get(self):
     59         """
     60         >>> print SampleClass(-5).get()
     61         -5
     62         """
     63         return self.val
     64 
     65     def a_staticmethod(v):
     66         """
     67         >>> print SampleClass.a_staticmethod(10)
     68         11
     69         """
     70         return v+1
     71     a_staticmethod = staticmethod(a_staticmethod)
     72 
     73     def a_classmethod(cls, v):
     74         """
     75         >>> print SampleClass.a_classmethod(10)
     76         12
     77         >>> print SampleClass(0).a_classmethod(10)
     78         12
     79         """
     80         return v+2
     81     a_classmethod = classmethod(a_classmethod)
     82 
     83     a_property = property(get, doc="""
     84         >>> print SampleClass(22).a_property
     85         22
     86         """)
     87 
     88     class NestedClass:
     89         """
     90         >>> x = SampleClass.NestedClass(5)
     91         >>> y = x.square()
     92         >>> print y.get()
     93         25
     94         """
     95         def __init__(self, val=0):
     96             """
     97             >>> print SampleClass.NestedClass().get()
     98             0
     99             """
    100             self.val = val
    101         def square(self):
    102             return SampleClass.NestedClass(self.val*self.val)
    103         def get(self):
    104             return self.val
    105 
    106 class SampleNewStyleClass(object):
    107     r"""
    108     >>> print '1\n2\n3'
    109     1
    110     2
    111     3
    112     """
    113     def __init__(self, val):
    114         """
    115         >>> print SampleNewStyleClass(12).get()
    116         12
    117         """
    118         self.val = val
    119 
    120     def double(self):
    121         """
    122         >>> print SampleNewStyleClass(12).double().get()
    123         24
    124         """
    125         return SampleNewStyleClass(self.val + self.val)
    126 
    127     def get(self):
    128         """
    129         >>> print SampleNewStyleClass(-5).get()
    130         -5
    131         """
    132         return self.val
    133 
    134 ######################################################################
    135 ## Fake stdin (for testing interactive debugging)
    136 ######################################################################
    137 
    138 class _FakeInput:
    139     """
    140     A fake input stream for pdb's interactive debugger.  Whenever a
    141     line is read, print it (to simulate the user typing it), and then
    142     return it.  The set of lines to return is specified in the
    143     constructor; they should not have trailing newlines.
    144     """
    145     def __init__(self, lines):
    146         self.lines = lines
    147 
    148     def readline(self):
    149         line = self.lines.pop(0)
    150         print line
    151         return line+'\n'
    152 
    153 ######################################################################
    154 ## Test Cases
    155 ######################################################################
    156 
    157 def test_Example(): r"""
    158 Unit tests for the `Example` class.
    159 
    160 Example is a simple container class that holds:
    161   - `source`: A source string.
    162   - `want`: An expected output string.
    163   - `exc_msg`: An expected exception message string (or None if no
    164     exception is expected).
    165   - `lineno`: A line number (within the docstring).
    166   - `indent`: The example's indentation in the input string.
    167   - `options`: An option dictionary, mapping option flags to True or
    168     False.
    169 
    170 These attributes are set by the constructor.  `source` and `want` are
    171 required; the other attributes all have default values:
    172 
    173     >>> example = doctest.Example('print 1', '1\n')
    174     >>> (example.source, example.want, example.exc_msg,
    175     ...  example.lineno, example.indent, example.options)
    176     ('print 1\n', '1\n', None, 0, 0, {})
    177 
    178 The first three attributes (`source`, `want`, and `exc_msg`) may be
    179 specified positionally; the remaining arguments should be specified as
    180 keyword arguments:
    181 
    182     >>> exc_msg = 'IndexError: pop from an empty list'
    183     >>> example = doctest.Example('[].pop()', '', exc_msg,
    184     ...                           lineno=5, indent=4,
    185     ...                           options={doctest.ELLIPSIS: True})
    186     >>> (example.source, example.want, example.exc_msg,
    187     ...  example.lineno, example.indent, example.options)
    188     ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
    189 
    190 The constructor normalizes the `source` string to end in a newline:
    191 
    192     Source spans a single line: no terminating newline.
    193     >>> e = doctest.Example('print 1', '1\n')
    194     >>> e.source, e.want
    195     ('print 1\n', '1\n')
    196 
    197     >>> e = doctest.Example('print 1\n', '1\n')
    198     >>> e.source, e.want
    199     ('print 1\n', '1\n')
    200 
    201     Source spans multiple lines: require terminating newline.
    202     >>> e = doctest.Example('print 1;\nprint 2\n', '1\n2\n')
    203     >>> e.source, e.want
    204     ('print 1;\nprint 2\n', '1\n2\n')
    205 
    206     >>> e = doctest.Example('print 1;\nprint 2', '1\n2\n')
    207     >>> e.source, e.want
    208     ('print 1;\nprint 2\n', '1\n2\n')
    209 
    210     Empty source string (which should never appear in real examples)
    211     >>> e = doctest.Example('', '')
    212     >>> e.source, e.want
    213     ('\n', '')
    214 
    215 The constructor normalizes the `want` string to end in a newline,
    216 unless it's the empty string:
    217 
    218     >>> e = doctest.Example('print 1', '1\n')
    219     >>> e.source, e.want
    220     ('print 1\n', '1\n')
    221 
    222     >>> e = doctest.Example('print 1', '1')
    223     >>> e.source, e.want
    224     ('print 1\n', '1\n')
    225 
    226     >>> e = doctest.Example('print', '')
    227     >>> e.source, e.want
    228     ('print\n', '')
    229 
    230 The constructor normalizes the `exc_msg` string to end in a newline,
    231 unless it's `None`:
    232 
    233     Message spans one line
    234     >>> exc_msg = 'IndexError: pop from an empty list'
    235     >>> e = doctest.Example('[].pop()', '', exc_msg)
    236     >>> e.exc_msg
    237     'IndexError: pop from an empty list\n'
    238 
    239     >>> exc_msg = 'IndexError: pop from an empty list\n'
    240     >>> e = doctest.Example('[].pop()', '', exc_msg)
    241     >>> e.exc_msg
    242     'IndexError: pop from an empty list\n'
    243 
    244     Message spans multiple lines
    245     >>> exc_msg = 'ValueError: 1\n  2'
    246     >>> e = doctest.Example('raise ValueError("1\n  2")', '', exc_msg)
    247     >>> e.exc_msg
    248     'ValueError: 1\n  2\n'
    249 
    250     >>> exc_msg = 'ValueError: 1\n  2\n'
    251     >>> e = doctest.Example('raise ValueError("1\n  2")', '', exc_msg)
    252     >>> e.exc_msg
    253     'ValueError: 1\n  2\n'
    254 
    255     Empty (but non-None) exception message (which should never appear
    256     in real examples)
    257     >>> exc_msg = ''
    258     >>> e = doctest.Example('raise X()', '', exc_msg)
    259     >>> e.exc_msg
    260     '\n'
    261 
    262 Compare `Example`:
    263     >>> example = doctest.Example('print 1', '1\n')
    264     >>> same_example = doctest.Example('print 1', '1\n')
    265     >>> other_example = doctest.Example('print 42', '42\n')
    266     >>> example == same_example
    267     True
    268     >>> example != same_example
    269     False
    270     >>> hash(example) == hash(same_example)
    271     True
    272     >>> example == other_example
    273     False
    274     >>> example != other_example
    275     True
    276 """
    277 
    278 def test_DocTest(): r"""
    279 Unit tests for the `DocTest` class.
    280 
    281 DocTest is a collection of examples, extracted from a docstring, along
    282 with information about where the docstring comes from (a name,
    283 filename, and line number).  The docstring is parsed by the `DocTest`
    284 constructor:
    285 
    286     >>> docstring = '''
    287     ...     >>> print 12
    288     ...     12
    289     ...
    290     ... Non-example text.
    291     ...
    292     ...     >>> print 'another\example'
    293     ...     another
    294     ...     example
    295     ... '''
    296     >>> globs = {} # globals to run the test in.
    297     >>> parser = doctest.DocTestParser()
    298     >>> test = parser.get_doctest(docstring, globs, 'some_test',
    299     ...                           'some_file', 20)
    300     >>> print test
    301     <DocTest some_test from some_file:20 (2 examples)>
    302     >>> len(test.examples)
    303     2
    304     >>> e1, e2 = test.examples
    305     >>> (e1.source, e1.want, e1.lineno)
    306     ('print 12\n', '12\n', 1)
    307     >>> (e2.source, e2.want, e2.lineno)
    308     ("print 'another\\example'\n", 'another\nexample\n', 6)
    309 
    310 Source information (name, filename, and line number) is available as
    311 attributes on the doctest object:
    312 
    313     >>> (test.name, test.filename, test.lineno)
    314     ('some_test', 'some_file', 20)
    315 
    316 The line number of an example within its containing file is found by
    317 adding the line number of the example and the line number of its
    318 containing test:
    319 
    320     >>> test.lineno + e1.lineno
    321     21
    322     >>> test.lineno + e2.lineno
    323     26
    324 
    325 If the docstring contains inconsistent leading whitespace in the
    326 expected output of an example, then `DocTest` will raise a ValueError:
    327 
    328     >>> docstring = r'''
    329     ...       >>> print 'bad\nindentation'
    330     ...       bad
    331     ...     indentation
    332     ...     '''
    333     >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
    334     Traceback (most recent call last):
    335     ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
    336 
    337 If the docstring contains inconsistent leading whitespace on
    338 continuation lines, then `DocTest` will raise a ValueError:
    339 
    340     >>> docstring = r'''
    341     ...       >>> print ('bad indentation',
    342     ...     ...          2)
    343     ...       ('bad', 'indentation')
    344     ...     '''
    345     >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
    346     Traceback (most recent call last):
    347     ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '...          2)'
    348 
    349 If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
    350 will raise a ValueError:
    351 
    352     >>> docstring = '>>>print 1\n1'
    353     >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
    354     Traceback (most recent call last):
    355     ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print 1'
    356 
    357 If there's no blank space after a PS2 prompt ('...'), then `DocTest`
    358 will raise a ValueError:
    359 
    360     >>> docstring = '>>> if 1:\n...print 1\n1'
    361     >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
    362     Traceback (most recent call last):
    363     ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print 1'
    364 
    365 Compare `DocTest`:
    366 
    367     >>> docstring = '''
    368     ...     >>> print 12
    369     ...     12
    370     ... '''
    371     >>> test = parser.get_doctest(docstring, globs, 'some_test',
    372     ...                           'some_test', 20)
    373     >>> same_test = parser.get_doctest(docstring, globs, 'some_test',
    374     ...                                'some_test', 20)
    375     >>> test == same_test
    376     True
    377     >>> test != same_test
    378     False
    379     >>> hash(test) == hash(same_test)
    380     True
    381     >>> docstring = '''
    382     ...     >>> print 42
    383     ...     42
    384     ... '''
    385     >>> other_test = parser.get_doctest(docstring, globs, 'other_test',
    386     ...                                 'other_file', 10)
    387     >>> test == other_test
    388     False
    389     >>> test != other_test
    390     True
    391 
    392 Compare `DocTestCase`:
    393 
    394     >>> DocTestCase = doctest.DocTestCase
    395     >>> test_case = DocTestCase(test)
    396     >>> same_test_case = DocTestCase(same_test)
    397     >>> other_test_case = DocTestCase(other_test)
    398     >>> test_case == same_test_case
    399     True
    400     >>> test_case != same_test_case
    401     False
    402     >>> hash(test_case) == hash(same_test_case)
    403     True
    404     >>> test == other_test_case
    405     False
    406     >>> test != other_test_case
    407     True
    408 
    409 """
    410 
    411 def test_DocTestFinder(): r"""
    412 Unit tests for the `DocTestFinder` class.
    413 
    414 DocTestFinder is used to extract DocTests from an object's docstring
    415 and the docstrings of its contained objects.  It can be used with
    416 modules, functions, classes, methods, staticmethods, classmethods, and
    417 properties.
    418 
    419 Finding Tests in Functions
    420 ~~~~~~~~~~~~~~~~~~~~~~~~~~
    421 For a function whose docstring contains examples, DocTestFinder.find()
    422 will return a single test (for that function's docstring):
    423 
    424     >>> finder = doctest.DocTestFinder()
    425 
    426 We'll simulate a __file__ attr that ends in pyc:
    427 
    428     >>> import test.test_doctest
    429     >>> old = test.test_doctest.__file__
    430     >>> test.test_doctest.__file__ = 'test_doctest.pyc'
    431 
    432     >>> tests = finder.find(sample_func)
    433 
    434     >>> print tests  # doctest: +ELLIPSIS
    435     [<DocTest sample_func from ...:17 (1 example)>]
    436 
    437 The exact name depends on how test_doctest was invoked, so allow for
    438 leading path components.
    439 
    440     >>> tests[0].filename # doctest: +ELLIPSIS
    441     '...test_doctest.py'
    442 
    443     >>> test.test_doctest.__file__ = old
    444 
    445 
    446     >>> e = tests[0].examples[0]
    447     >>> (e.source, e.want, e.lineno)
    448     ('print sample_func(22)\n', '44\n', 3)
    449 
    450 By default, tests are created for objects with no docstring:
    451 
    452     >>> def no_docstring(v):
    453     ...     pass
    454     >>> finder.find(no_docstring)
    455     []
    456 
    457 However, the optional argument `exclude_empty` to the DocTestFinder
    458 constructor can be used to exclude tests for objects with empty
    459 docstrings:
    460 
    461     >>> def no_docstring(v):
    462     ...     pass
    463     >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
    464     >>> excl_empty_finder.find(no_docstring)
    465     []
    466 
    467 If the function has a docstring with no examples, then a test with no
    468 examples is returned.  (This lets `DocTestRunner` collect statistics
    469 about which functions have no tests -- but is that useful?  And should
    470 an empty test also be created when there's no docstring?)
    471 
    472     >>> def no_examples(v):
    473     ...     ''' no doctest examples '''
    474     >>> finder.find(no_examples) # doctest: +ELLIPSIS
    475     [<DocTest no_examples from ...:1 (no examples)>]
    476 
    477 Finding Tests in Classes
    478 ~~~~~~~~~~~~~~~~~~~~~~~~
    479 For a class, DocTestFinder will create a test for the class's
    480 docstring, and will recursively explore its contents, including
    481 methods, classmethods, staticmethods, properties, and nested classes.
    482 
    483     >>> finder = doctest.DocTestFinder()
    484     >>> tests = finder.find(SampleClass)
    485     >>> for t in tests:
    486     ...     print '%2s  %s' % (len(t.examples), t.name)
    487      3  SampleClass
    488      3  SampleClass.NestedClass
    489      1  SampleClass.NestedClass.__init__
    490      1  SampleClass.__init__
    491      2  SampleClass.a_classmethod
    492      1  SampleClass.a_property
    493      1  SampleClass.a_staticmethod
    494      1  SampleClass.double
    495      1  SampleClass.get
    496 
    497 New-style classes are also supported:
    498 
    499     >>> tests = finder.find(SampleNewStyleClass)
    500     >>> for t in tests:
    501     ...     print '%2s  %s' % (len(t.examples), t.name)
    502      1  SampleNewStyleClass
    503      1  SampleNewStyleClass.__init__
    504      1  SampleNewStyleClass.double
    505      1  SampleNewStyleClass.get
    506 
    507 Finding Tests in Modules
    508 ~~~~~~~~~~~~~~~~~~~~~~~~
    509 For a module, DocTestFinder will create a test for the class's
    510 docstring, and will recursively explore its contents, including
    511 functions, classes, and the `__test__` dictionary, if it exists:
    512 
    513     >>> # A module
    514     >>> import types
    515     >>> m = types.ModuleType('some_module')
    516     >>> def triple(val):
    517     ...     '''
    518     ...     >>> print triple(11)
    519     ...     33
    520     ...     '''
    521     ...     return val*3
    522     >>> m.__dict__.update({
    523     ...     'sample_func': sample_func,
    524     ...     'SampleClass': SampleClass,
    525     ...     '__doc__': '''
    526     ...         Module docstring.
    527     ...             >>> print 'module'
    528     ...             module
    529     ...         ''',
    530     ...     '__test__': {
    531     ...         'd': '>>> print 6\n6\n>>> print 7\n7\n',
    532     ...         'c': triple}})
    533 
    534     >>> finder = doctest.DocTestFinder()
    535     >>> # Use module=test.test_doctest, to prevent doctest from
    536     >>> # ignoring the objects since they weren't defined in m.
    537     >>> import test.test_doctest
    538     >>> tests = finder.find(m, module=test.test_doctest)
    539     >>> for t in tests:
    540     ...     print '%2s  %s' % (len(t.examples), t.name)
    541      1  some_module
    542      3  some_module.SampleClass
    543      3  some_module.SampleClass.NestedClass
    544      1  some_module.SampleClass.NestedClass.__init__
    545      1  some_module.SampleClass.__init__
    546      2  some_module.SampleClass.a_classmethod
    547      1  some_module.SampleClass.a_property
    548      1  some_module.SampleClass.a_staticmethod
    549      1  some_module.SampleClass.double
    550      1  some_module.SampleClass.get
    551      1  some_module.__test__.c
    552      2  some_module.__test__.d
    553      1  some_module.sample_func
    554 
    555 Duplicate Removal
    556 ~~~~~~~~~~~~~~~~~
    557 If a single object is listed twice (under different names), then tests
    558 will only be generated for it once:
    559 
    560     >>> from test import doctest_aliases
    561     >>> assert doctest_aliases.TwoNames.f
    562     >>> assert doctest_aliases.TwoNames.g
    563     >>> tests = excl_empty_finder.find(doctest_aliases)
    564     >>> print len(tests)
    565     2
    566     >>> print tests[0].name
    567     test.doctest_aliases.TwoNames
    568 
    569     TwoNames.f and TwoNames.g are bound to the same object.
    570     We can't guess which will be found in doctest's traversal of
    571     TwoNames.__dict__ first, so we have to allow for either.
    572 
    573     >>> tests[1].name.split('.')[-1] in ['f', 'g']
    574     True
    575 
    576 Empty Tests
    577 ~~~~~~~~~~~
    578 By default, an object with no doctests doesn't create any tests:
    579 
    580     >>> tests = doctest.DocTestFinder().find(SampleClass)
    581     >>> for t in tests:
    582     ...     print '%2s  %s' % (len(t.examples), t.name)
    583      3  SampleClass
    584      3  SampleClass.NestedClass
    585      1  SampleClass.NestedClass.__init__
    586      1  SampleClass.__init__
    587      2  SampleClass.a_classmethod
    588      1  SampleClass.a_property
    589      1  SampleClass.a_staticmethod
    590      1  SampleClass.double
    591      1  SampleClass.get
    592 
    593 By default, that excluded objects with no doctests.  exclude_empty=False
    594 tells it to include (empty) tests for objects with no doctests.  This feature
    595 is really to support backward compatibility in what doctest.master.summarize()
    596 displays.
    597 
    598     >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
    599     >>> for t in tests:
    600     ...     print '%2s  %s' % (len(t.examples), t.name)
    601      3  SampleClass
    602      3  SampleClass.NestedClass
    603      1  SampleClass.NestedClass.__init__
    604      0  SampleClass.NestedClass.get
    605      0  SampleClass.NestedClass.square
    606      1  SampleClass.__init__
    607      2  SampleClass.a_classmethod
    608      1  SampleClass.a_property
    609      1  SampleClass.a_staticmethod
    610      1  SampleClass.double
    611      1  SampleClass.get
    612 
    613 Turning off Recursion
    614 ~~~~~~~~~~~~~~~~~~~~~
    615 DocTestFinder can be told not to look for tests in contained objects
    616 using the `recurse` flag:
    617 
    618     >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
    619     >>> for t in tests:
    620     ...     print '%2s  %s' % (len(t.examples), t.name)
    621      3  SampleClass
    622 
    623 Line numbers
    624 ~~~~~~~~~~~~
    625 DocTestFinder finds the line number of each example:
    626 
    627     >>> def f(x):
    628     ...     '''
    629     ...     >>> x = 12
    630     ...
    631     ...     some text
    632     ...
    633     ...     >>> # examples are not created for comments & bare prompts.
    634     ...     >>>
    635     ...     ...
    636     ...
    637     ...     >>> for x in range(10):
    638     ...     ...     print x,
    639     ...     0 1 2 3 4 5 6 7 8 9
    640     ...     >>> x//2
    641     ...     6
    642     ...     '''
    643     >>> test = doctest.DocTestFinder().find(f)[0]
    644     >>> [e.lineno for e in test.examples]
    645     [1, 9, 12]
    646 """
    647 
    648 def test_DocTestParser(): r"""
    649 Unit tests for the `DocTestParser` class.
    650 
    651 DocTestParser is used to parse docstrings containing doctest examples.
    652 
    653 The `parse` method divides a docstring into examples and intervening
    654 text:
    655 
    656     >>> s = '''
    657     ...     >>> x, y = 2, 3  # no output expected
    658     ...     >>> if 1:
    659     ...     ...     print x
    660     ...     ...     print y
    661     ...     2
    662     ...     3
    663     ...
    664     ...     Some text.
    665     ...     >>> x+y
    666     ...     5
    667     ...     '''
    668     >>> parser = doctest.DocTestParser()
    669     >>> for piece in parser.parse(s):
    670     ...     if isinstance(piece, doctest.Example):
    671     ...         print 'Example:', (piece.source, piece.want, piece.lineno)
    672     ...     else:
    673     ...         print '   Text:', `piece`
    674        Text: '\n'
    675     Example: ('x, y = 2, 3  # no output expected\n', '', 1)
    676        Text: ''
    677     Example: ('if 1:\n    print x\n    print y\n', '2\n3\n', 2)
    678        Text: '\nSome text.\n'
    679     Example: ('x+y\n', '5\n', 9)
    680        Text: ''
    681 
    682 The `get_examples` method returns just the examples:
    683 
    684     >>> for piece in parser.get_examples(s):
    685     ...     print (piece.source, piece.want, piece.lineno)
    686     ('x, y = 2, 3  # no output expected\n', '', 1)
    687     ('if 1:\n    print x\n    print y\n', '2\n3\n', 2)
    688     ('x+y\n', '5\n', 9)
    689 
    690 The `get_doctest` method creates a Test from the examples, along with the
    691 given arguments:
    692 
    693     >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
    694     >>> (test.name, test.filename, test.lineno)
    695     ('name', 'filename', 5)
    696     >>> for piece in test.examples:
    697     ...     print (piece.source, piece.want, piece.lineno)
    698     ('x, y = 2, 3  # no output expected\n', '', 1)
    699     ('if 1:\n    print x\n    print y\n', '2\n3\n', 2)
    700     ('x+y\n', '5\n', 9)
    701 """
    702 
    703 class test_DocTestRunner:
    704     def basics(): r"""
    705 Unit tests for the `DocTestRunner` class.
    706 
    707 DocTestRunner is used to run DocTest test cases, and to accumulate
    708 statistics.  Here's a simple DocTest case we can use:
    709 
    710     >>> def f(x):
    711     ...     '''
    712     ...     >>> x = 12
    713     ...     >>> print x
    714     ...     12
    715     ...     >>> x//2
    716     ...     6
    717     ...     '''
    718     >>> test = doctest.DocTestFinder().find(f)[0]
    719 
    720 The main DocTestRunner interface is the `run` method, which runs a
    721 given DocTest case in a given namespace (globs).  It returns a tuple
    722 `(f,t)`, where `f` is the number of failed tests and `t` is the number
    723 of tried tests.
    724 
    725     >>> doctest.DocTestRunner(verbose=False).run(test)
    726     TestResults(failed=0, attempted=3)
    727 
    728 If any example produces incorrect output, then the test runner reports
    729 the failure and proceeds to the next example:
    730 
    731     >>> def f(x):
    732     ...     '''
    733     ...     >>> x = 12
    734     ...     >>> print x
    735     ...     14
    736     ...     >>> x//2
    737     ...     6
    738     ...     '''
    739     >>> test = doctest.DocTestFinder().find(f)[0]
    740     >>> doctest.DocTestRunner(verbose=True).run(test)
    741     ... # doctest: +ELLIPSIS
    742     Trying:
    743         x = 12
    744     Expecting nothing
    745     ok
    746     Trying:
    747         print x
    748     Expecting:
    749         14
    750     **********************************************************************
    751     File ..., line 4, in f
    752     Failed example:
    753         print x
    754     Expected:
    755         14
    756     Got:
    757         12
    758     Trying:
    759         x//2
    760     Expecting:
    761         6
    762     ok
    763     TestResults(failed=1, attempted=3)
    764 """
    765     def verbose_flag(): r"""
    766 The `verbose` flag makes the test runner generate more detailed
    767 output:
    768 
    769     >>> def f(x):
    770     ...     '''
    771     ...     >>> x = 12
    772     ...     >>> print x
    773     ...     12
    774     ...     >>> x//2
    775     ...     6
    776     ...     '''
    777     >>> test = doctest.DocTestFinder().find(f)[0]
    778 
    779     >>> doctest.DocTestRunner(verbose=True).run(test)
    780     Trying:
    781         x = 12
    782     Expecting nothing
    783     ok
    784     Trying:
    785         print x
    786     Expecting:
    787         12
    788     ok
    789     Trying:
    790         x//2
    791     Expecting:
    792         6
    793     ok
    794     TestResults(failed=0, attempted=3)
    795 
    796 If the `verbose` flag is unspecified, then the output will be verbose
    797 iff `-v` appears in sys.argv:
    798 
    799     >>> # Save the real sys.argv list.
    800     >>> old_argv = sys.argv
    801 
    802     >>> # If -v does not appear in sys.argv, then output isn't verbose.
    803     >>> sys.argv = ['test']
    804     >>> doctest.DocTestRunner().run(test)
    805     TestResults(failed=0, attempted=3)
    806 
    807     >>> # If -v does appear in sys.argv, then output is verbose.
    808     >>> sys.argv = ['test', '-v']
    809     >>> doctest.DocTestRunner().run(test)
    810     Trying:
    811         x = 12
    812     Expecting nothing
    813     ok
    814     Trying:
    815         print x
    816     Expecting:
    817         12
    818     ok
    819     Trying:
    820         x//2
    821     Expecting:
    822         6
    823     ok
    824     TestResults(failed=0, attempted=3)
    825 
    826     >>> # Restore sys.argv
    827     >>> sys.argv = old_argv
    828 
    829 In the remaining examples, the test runner's verbosity will be
    830 explicitly set, to ensure that the test behavior is consistent.
    831     """
    832     def exceptions(): r"""
    833 Tests of `DocTestRunner`'s exception handling.
    834 
    835 An expected exception is specified with a traceback message.  The
    836 lines between the first line and the type/value may be omitted or
    837 replaced with any other string:
    838 
    839     >>> def f(x):
    840     ...     '''
    841     ...     >>> x = 12
    842     ...     >>> print x//0
    843     ...     Traceback (most recent call last):
    844     ...     ZeroDivisionError: integer division or modulo by zero
    845     ...     '''
    846     >>> test = doctest.DocTestFinder().find(f)[0]
    847     >>> doctest.DocTestRunner(verbose=False).run(test)
    848     TestResults(failed=0, attempted=2)
    849 
    850 An example may not generate output before it raises an exception; if
    851 it does, then the traceback message will not be recognized as
    852 signaling an expected exception, so the example will be reported as an
    853 unexpected exception:
    854 
    855     >>> def f(x):
    856     ...     '''
    857     ...     >>> x = 12
    858     ...     >>> print 'pre-exception output', x//0
    859     ...     pre-exception output
    860     ...     Traceback (most recent call last):
    861     ...     ZeroDivisionError: integer division or modulo by zero
    862     ...     '''
    863     >>> test = doctest.DocTestFinder().find(f)[0]
    864     >>> doctest.DocTestRunner(verbose=False).run(test)
    865     ... # doctest: +ELLIPSIS
    866     **********************************************************************
    867     File ..., line 4, in f
    868     Failed example:
    869         print 'pre-exception output', x//0
    870     Exception raised:
    871         ...
    872         ZeroDivisionError: integer division or modulo by zero
    873     TestResults(failed=1, attempted=2)
    874 
    875 Exception messages may contain newlines:
    876 
    877     >>> def f(x):
    878     ...     r'''
    879     ...     >>> raise ValueError, 'multi\nline\nmessage'
    880     ...     Traceback (most recent call last):
    881     ...     ValueError: multi
    882     ...     line
    883     ...     message
    884     ...     '''
    885     >>> test = doctest.DocTestFinder().find(f)[0]
    886     >>> doctest.DocTestRunner(verbose=False).run(test)
    887     TestResults(failed=0, attempted=1)
    888 
    889 If an exception is expected, but an exception with the wrong type or
    890 message is raised, then it is reported as a failure:
    891 
    892     >>> def f(x):
    893     ...     r'''
    894     ...     >>> raise ValueError, 'message'
    895     ...     Traceback (most recent call last):
    896     ...     ValueError: wrong message
    897     ...     '''
    898     >>> test = doctest.DocTestFinder().find(f)[0]
    899     >>> doctest.DocTestRunner(verbose=False).run(test)
    900     ... # doctest: +ELLIPSIS
    901     **********************************************************************
    902     File ..., line 3, in f
    903     Failed example:
    904         raise ValueError, 'message'
    905     Expected:
    906         Traceback (most recent call last):
    907         ValueError: wrong message
    908     Got:
    909         Traceback (most recent call last):
    910         ...
    911         ValueError: message
    912     TestResults(failed=1, attempted=1)
    913 
    914 However, IGNORE_EXCEPTION_DETAIL can be used to allow a mismatch in the
    915 detail:
    916 
    917     >>> def f(x):
    918     ...     r'''
    919     ...     >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
    920     ...     Traceback (most recent call last):
    921     ...     ValueError: wrong message
    922     ...     '''
    923     >>> test = doctest.DocTestFinder().find(f)[0]
    924     >>> doctest.DocTestRunner(verbose=False).run(test)
    925     TestResults(failed=0, attempted=1)
    926 
    927 IGNORE_EXCEPTION_DETAIL also ignores difference in exception formatting
    928 between Python versions. For example, in Python 3.x, the module path of
    929 the exception is in the output, but this will fail under Python 2:
    930 
    931     >>> def f(x):
    932     ...     r'''
    933     ...     >>> from httplib import HTTPException
    934     ...     >>> raise HTTPException('message')
    935     ...     Traceback (most recent call last):
    936     ...     httplib.HTTPException: message
    937     ...     '''
    938     >>> test = doctest.DocTestFinder().find(f)[0]
    939     >>> doctest.DocTestRunner(verbose=False).run(test)
    940     ... # doctest: +ELLIPSIS
    941     **********************************************************************
    942     File ..., line 4, in f
    943     Failed example:
    944         raise HTTPException('message')
    945     Expected:
    946         Traceback (most recent call last):
    947         httplib.HTTPException: message
    948     Got:
    949         Traceback (most recent call last):
    950         ...
    951         HTTPException: message
    952     TestResults(failed=1, attempted=2)
    953 
    954 But in Python 2 the module path is not included, and therefore a test must look
    955 like the following test to succeed in Python 2. But that test will fail under
    956 Python 3.
    957 
    958     >>> def f(x):
    959     ...     r'''
    960     ...     >>> from httplib import HTTPException
    961     ...     >>> raise HTTPException('message')
    962     ...     Traceback (most recent call last):
    963     ...     HTTPException: message
    964     ...     '''
    965     >>> test = doctest.DocTestFinder().find(f)[0]
    966     >>> doctest.DocTestRunner(verbose=False).run(test)
    967     TestResults(failed=0, attempted=2)
    968 
    969 However, with IGNORE_EXCEPTION_DETAIL, the module name of the exception
    970 (if any) will be ignored:
    971 
    972     >>> def f(x):
    973     ...     r'''
    974     ...     >>> from httplib import HTTPException
    975     ...     >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
    976     ...     Traceback (most recent call last):
    977     ...     HTTPException: message
    978     ...     '''
    979     >>> test = doctest.DocTestFinder().find(f)[0]
    980     >>> doctest.DocTestRunner(verbose=False).run(test)
    981     TestResults(failed=0, attempted=2)
    982 
    983 The module path will be completely ignored, so two different module paths will
    984 still pass if IGNORE_EXCEPTION_DETAIL is given. This is intentional, so it can
    985 be used when exceptions have changed module.
    986 
    987     >>> def f(x):
    988     ...     r'''
    989     ...     >>> from httplib import HTTPException
    990     ...     >>> raise HTTPException('message') #doctest: +IGNORE_EXCEPTION_DETAIL
    991     ...     Traceback (most recent call last):
    992     ...     foo.bar.HTTPException: message
    993     ...     '''
    994     >>> test = doctest.DocTestFinder().find(f)[0]
    995     >>> doctest.DocTestRunner(verbose=False).run(test)
    996     TestResults(failed=0, attempted=2)
    997 
    998 But IGNORE_EXCEPTION_DETAIL does not allow a mismatch in the exception type:
    999 
   1000     >>> def f(x):
   1001     ...     r'''
   1002     ...     >>> raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
   1003     ...     Traceback (most recent call last):
   1004     ...     TypeError: wrong type
   1005     ...     '''
   1006     >>> test = doctest.DocTestFinder().find(f)[0]
   1007     >>> doctest.DocTestRunner(verbose=False).run(test)
   1008     ... # doctest: +ELLIPSIS
   1009     **********************************************************************
   1010     File ..., line 3, in f
   1011     Failed example:
   1012         raise ValueError, 'message' #doctest: +IGNORE_EXCEPTION_DETAIL
   1013     Expected:
   1014         Traceback (most recent call last):
   1015         TypeError: wrong type
   1016     Got:
   1017         Traceback (most recent call last):
   1018         ...
   1019         ValueError: message
   1020     TestResults(failed=1, attempted=1)
   1021 
   1022 If the exception does not have a message, you can still use
   1023 IGNORE_EXCEPTION_DETAIL to normalize the modules between Python 2 and 3:
   1024 
   1025     >>> def f(x):
   1026     ...     r'''
   1027     ...     >>> from Queue import Empty
   1028     ...     >>> raise Empty() #doctest: +IGNORE_EXCEPTION_DETAIL
   1029     ...     Traceback (most recent call last):
   1030     ...     foo.bar.Empty
   1031     ...     '''
   1032     >>> test = doctest.DocTestFinder().find(f)[0]
   1033     >>> doctest.DocTestRunner(verbose=False).run(test)
   1034     TestResults(failed=0, attempted=2)
   1035 
   1036 Note that a trailing colon doesn't matter either:
   1037 
   1038     >>> def f(x):
   1039     ...     r'''
   1040     ...     >>> from Queue import Empty
   1041     ...     >>> raise Empty() #doctest: +IGNORE_EXCEPTION_DETAIL
   1042     ...     Traceback (most recent call last):
   1043     ...     foo.bar.Empty:
   1044     ...     '''
   1045     >>> test = doctest.DocTestFinder().find(f)[0]
   1046     >>> doctest.DocTestRunner(verbose=False).run(test)
   1047     TestResults(failed=0, attempted=2)
   1048 
   1049 If an exception is raised but not expected, then it is reported as an
   1050 unexpected exception:
   1051 
   1052     >>> def f(x):
   1053     ...     r'''
   1054     ...     >>> 1//0
   1055     ...     0
   1056     ...     '''
   1057     >>> test = doctest.DocTestFinder().find(f)[0]
   1058     >>> doctest.DocTestRunner(verbose=False).run(test)
   1059     ... # doctest: +ELLIPSIS
   1060     **********************************************************************
   1061     File ..., line 3, in f
   1062     Failed example:
   1063         1//0
   1064     Exception raised:
   1065         Traceback (most recent call last):
   1066         ...
   1067         ZeroDivisionError: integer division or modulo by zero
   1068     TestResults(failed=1, attempted=1)
   1069 """
   1070     def displayhook(): r"""
   1071 Test that changing sys.displayhook doesn't matter for doctest.
   1072 
   1073     >>> import sys
   1074     >>> orig_displayhook = sys.displayhook
   1075     >>> def my_displayhook(x):
   1076     ...     print('hi!')
   1077     >>> sys.displayhook = my_displayhook
   1078     >>> def f():
   1079     ...     '''
   1080     ...     >>> 3
   1081     ...     3
   1082     ...     '''
   1083     >>> test = doctest.DocTestFinder().find(f)[0]
   1084     >>> r = doctest.DocTestRunner(verbose=False).run(test)
   1085     >>> post_displayhook = sys.displayhook
   1086 
   1087     We need to restore sys.displayhook now, so that we'll be able to test
   1088     results.
   1089 
   1090     >>> sys.displayhook = orig_displayhook
   1091 
   1092     Ok, now we can check that everything is ok.
   1093 
   1094     >>> r
   1095     TestResults(failed=0, attempted=1)
   1096     >>> post_displayhook is my_displayhook
   1097     True
   1098 """
   1099     def optionflags(): r"""
   1100 Tests of `DocTestRunner`'s option flag handling.
   1101 
   1102 Several option flags can be used to customize the behavior of the test
   1103 runner.  These are defined as module constants in doctest, and passed
   1104 to the DocTestRunner constructor (multiple constants should be ORed
   1105 together).
   1106 
   1107 The DONT_ACCEPT_TRUE_FOR_1 flag disables matches between True/False
   1108 and 1/0:
   1109 
   1110     >>> def f(x):
   1111     ...     '>>> True\n1\n'
   1112 
   1113     >>> # Without the flag:
   1114     >>> test = doctest.DocTestFinder().find(f)[0]
   1115     >>> doctest.DocTestRunner(verbose=False).run(test)
   1116     TestResults(failed=0, attempted=1)
   1117 
   1118     >>> # With the flag:
   1119     >>> test = doctest.DocTestFinder().find(f)[0]
   1120     >>> flags = doctest.DONT_ACCEPT_TRUE_FOR_1
   1121     >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
   1122     ... # doctest: +ELLIPSIS
   1123     **********************************************************************
   1124     File ..., line 2, in f
   1125     Failed example:
   1126         True
   1127     Expected:
   1128         1
   1129     Got:
   1130         True
   1131     TestResults(failed=1, attempted=1)
   1132 
   1133 The DONT_ACCEPT_BLANKLINE flag disables the match between blank lines
   1134 and the '<BLANKLINE>' marker:
   1135 
   1136     >>> def f(x):
   1137     ...     '>>> print "a\\n\\nb"\na\n<BLANKLINE>\nb\n'
   1138 
   1139     >>> # Without the flag:
   1140     >>> test = doctest.DocTestFinder().find(f)[0]
   1141     >>> doctest.DocTestRunner(verbose=False).run(test)
   1142     TestResults(failed=0, attempted=1)
   1143 
   1144     >>> # With the flag:
   1145     >>> test = doctest.DocTestFinder().find(f)[0]
   1146     >>> flags = doctest.DONT_ACCEPT_BLANKLINE
   1147     >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
   1148     ... # doctest: +ELLIPSIS
   1149     **********************************************************************
   1150     File ..., line 2, in f
   1151     Failed example:
   1152         print "a\n\nb"
   1153     Expected:
   1154         a
   1155         <BLANKLINE>
   1156         b
   1157     Got:
   1158         a
   1159     <BLANKLINE>
   1160         b
   1161     TestResults(failed=1, attempted=1)
   1162 
   1163 The NORMALIZE_WHITESPACE flag causes all sequences of whitespace to be
   1164 treated as equal:
   1165 
   1166     >>> def f(x):
   1167     ...     '>>> print 1, 2, 3\n  1   2\n 3'
   1168 
   1169     >>> # Without the flag:
   1170     >>> test = doctest.DocTestFinder().find(f)[0]
   1171     >>> doctest.DocTestRunner(verbose=False).run(test)
   1172     ... # doctest: +ELLIPSIS
   1173     **********************************************************************
   1174     File ..., line 2, in f
   1175     Failed example:
   1176         print 1, 2, 3
   1177     Expected:
   1178           1   2
   1179          3
   1180     Got:
   1181         1 2 3
   1182     TestResults(failed=1, attempted=1)
   1183 
   1184     >>> # With the flag:
   1185     >>> test = doctest.DocTestFinder().find(f)[0]
   1186     >>> flags = doctest.NORMALIZE_WHITESPACE
   1187     >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
   1188     TestResults(failed=0, attempted=1)
   1189 
   1190     An example from the docs:
   1191     >>> print range(20) #doctest: +NORMALIZE_WHITESPACE
   1192     [0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
   1193     10,  11, 12, 13, 14, 15, 16, 17, 18, 19]
   1194 
   1195 The ELLIPSIS flag causes ellipsis marker ("...") in the expected
   1196 output to match any substring in the actual output:
   1197 
   1198     >>> def f(x):
   1199     ...     '>>> print range(15)\n[0, 1, 2, ..., 14]\n'
   1200 
   1201     >>> # Without the flag:
   1202     >>> test = doctest.DocTestFinder().find(f)[0]
   1203     >>> doctest.DocTestRunner(verbose=False).run(test)
   1204     ... # doctest: +ELLIPSIS
   1205     **********************************************************************
   1206     File ..., line 2, in f
   1207     Failed example:
   1208         print range(15)
   1209     Expected:
   1210         [0, 1, 2, ..., 14]
   1211     Got:
   1212         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
   1213     TestResults(failed=1, attempted=1)
   1214 
   1215     >>> # With the flag:
   1216     >>> test = doctest.DocTestFinder().find(f)[0]
   1217     >>> flags = doctest.ELLIPSIS
   1218     >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
   1219     TestResults(failed=0, attempted=1)
   1220 
   1221     ... also matches nothing:
   1222 
   1223     >>> for i in range(100):
   1224     ...     print i**2, #doctest: +ELLIPSIS
   1225     0 1...4...9 16 ... 36 49 64 ... 9801
   1226 
   1227     ... can be surprising; e.g., this test passes:
   1228 
   1229     >>> for i in range(21): #doctest: +ELLIPSIS
   1230     ...     print i,
   1231     0 1 2 ...1...2...0
   1232 
   1233     Examples from the docs:
   1234 
   1235     >>> print range(20) # doctest:+ELLIPSIS
   1236     [0, 1, ..., 18, 19]
   1237 
   1238     >>> print range(20) # doctest: +ELLIPSIS
   1239     ...                 # doctest: +NORMALIZE_WHITESPACE
   1240     [0,    1, ...,   18,    19]
   1241 
   1242 The SKIP flag causes an example to be skipped entirely.  I.e., the
   1243 example is not run.  It can be useful in contexts where doctest
   1244 examples serve as both documentation and test cases, and an example
   1245 should be included for documentation purposes, but should not be
   1246 checked (e.g., because its output is random, or depends on resources
   1247 which would be unavailable.)  The SKIP flag can also be used for
   1248 'commenting out' broken examples.
   1249 
   1250     >>> import unavailable_resource           # doctest: +SKIP
   1251     >>> unavailable_resource.do_something()   # doctest: +SKIP
   1252     >>> unavailable_resource.blow_up()        # doctest: +SKIP
   1253     Traceback (most recent call last):
   1254         ...
   1255     UncheckedBlowUpError:  Nobody checks me.
   1256 
   1257     >>> import random
   1258     >>> print random.random() # doctest: +SKIP
   1259     0.721216923889
   1260 
   1261 The REPORT_UDIFF flag causes failures that involve multi-line expected
   1262 and actual outputs to be displayed using a unified diff:
   1263 
   1264     >>> def f(x):
   1265     ...     r'''
   1266     ...     >>> print '\n'.join('abcdefg')
   1267     ...     a
   1268     ...     B
   1269     ...     c
   1270     ...     d
   1271     ...     f
   1272     ...     g
   1273     ...     h
   1274     ...     '''
   1275 
   1276     >>> # Without the flag:
   1277     >>> test = doctest.DocTestFinder().find(f)[0]
   1278     >>> doctest.DocTestRunner(verbose=False).run(test)
   1279     ... # doctest: +ELLIPSIS
   1280     **********************************************************************
   1281     File ..., line 3, in f
   1282     Failed example:
   1283         print '\n'.join('abcdefg')
   1284     Expected:
   1285         a
   1286         B
   1287         c
   1288         d
   1289         f
   1290         g
   1291         h
   1292     Got:
   1293         a
   1294         b
   1295         c
   1296         d
   1297         e
   1298         f
   1299         g
   1300     TestResults(failed=1, attempted=1)
   1301 
   1302     >>> # With the flag:
   1303     >>> test = doctest.DocTestFinder().find(f)[0]
   1304     >>> flags = doctest.REPORT_UDIFF
   1305     >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
   1306     ... # doctest: +ELLIPSIS
   1307     **********************************************************************
   1308     File ..., line 3, in f
   1309     Failed example:
   1310         print '\n'.join('abcdefg')
   1311     Differences (unified diff with -expected +actual):
   1312         @@ -1,7 +1,7 @@
   1313          a
   1314         -B
   1315         +b
   1316          c
   1317          d
   1318         +e
   1319          f
   1320          g
   1321         -h
   1322     TestResults(failed=1, attempted=1)
   1323 
   1324 The REPORT_CDIFF flag causes failures that involve multi-line expected
   1325 and actual outputs to be displayed using a context diff:
   1326 
   1327     >>> # Reuse f() from the REPORT_UDIFF example, above.
   1328     >>> test = doctest.DocTestFinder().find(f)[0]
   1329     >>> flags = doctest.REPORT_CDIFF
   1330     >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
   1331     ... # doctest: +ELLIPSIS
   1332     **********************************************************************
   1333     File ..., line 3, in f
   1334     Failed example:
   1335         print '\n'.join('abcdefg')
   1336     Differences (context diff with expected followed by actual):
   1337         ***************
   1338         *** 1,7 ****
   1339           a
   1340         ! B
   1341           c
   1342           d
   1343           f
   1344           g
   1345         - h
   1346         --- 1,7 ----
   1347           a
   1348         ! b
   1349           c
   1350           d
   1351         + e
   1352           f
   1353           g
   1354     TestResults(failed=1, attempted=1)
   1355 
   1356 
   1357 The REPORT_NDIFF flag causes failures to use the difflib.Differ algorithm
   1358 used by the popular ndiff.py utility.  This does intraline difference
   1359 marking, as well as interline differences.
   1360 
   1361     >>> def f(x):
   1362     ...     r'''
   1363     ...     >>> print "a b  c d e f g h i   j k l m"
   1364     ...     a b c d e f g h i j k 1 m
   1365     ...     '''
   1366     >>> test = doctest.DocTestFinder().find(f)[0]
   1367     >>> flags = doctest.REPORT_NDIFF
   1368     >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
   1369     ... # doctest: +ELLIPSIS
   1370     **********************************************************************
   1371     File ..., line 3, in f
   1372     Failed example:
   1373         print "a b  c d e f g h i   j k l m"
   1374     Differences (ndiff with -expected +actual):
   1375         - a b c d e f g h i j k 1 m
   1376         ?                       ^
   1377         + a b  c d e f g h i   j k l m
   1378         ?     +              ++    ^
   1379     TestResults(failed=1, attempted=1)
   1380 
   1381 The REPORT_ONLY_FIRST_FAILURE suppresses result output after the first
   1382 failing example:
   1383 
   1384     >>> def f(x):
   1385     ...     r'''
   1386     ...     >>> print 1 # first success
   1387     ...     1
   1388     ...     >>> print 2 # first failure
   1389     ...     200
   1390     ...     >>> print 3 # second failure
   1391     ...     300
   1392     ...     >>> print 4 # second success
   1393     ...     4
   1394     ...     >>> print 5 # third failure
   1395     ...     500
   1396     ...     '''
   1397     >>> test = doctest.DocTestFinder().find(f)[0]
   1398     >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
   1399     >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
   1400     ... # doctest: +ELLIPSIS
   1401     **********************************************************************
   1402     File ..., line 5, in f
   1403     Failed example:
   1404         print 2 # first failure
   1405     Expected:
   1406         200
   1407     Got:
   1408         2
   1409     TestResults(failed=3, attempted=5)
   1410 
   1411 However, output from `report_start` is not suppressed:
   1412 
   1413     >>> doctest.DocTestRunner(verbose=True, optionflags=flags).run(test)
   1414     ... # doctest: +ELLIPSIS
   1415     Trying:
   1416         print 1 # first success
   1417     Expecting:
   1418         1
   1419     ok
   1420     Trying:
   1421         print 2 # first failure
   1422     Expecting:
   1423         200
   1424     **********************************************************************
   1425     File ..., line 5, in f
   1426     Failed example:
   1427         print 2 # first failure
   1428     Expected:
   1429         200
   1430     Got:
   1431         2
   1432     TestResults(failed=3, attempted=5)
   1433 
   1434 For the purposes of REPORT_ONLY_FIRST_FAILURE, unexpected exceptions
   1435 count as failures:
   1436 
   1437     >>> def f(x):
   1438     ...     r'''
   1439     ...     >>> print 1 # first success
   1440     ...     1
   1441     ...     >>> raise ValueError(2) # first failure
   1442     ...     200
   1443     ...     >>> print 3 # second failure
   1444     ...     300
   1445     ...     >>> print 4 # second success
   1446     ...     4
   1447     ...     >>> print 5 # third failure
   1448     ...     500
   1449     ...     '''
   1450     >>> test = doctest.DocTestFinder().find(f)[0]
   1451     >>> flags = doctest.REPORT_ONLY_FIRST_FAILURE
   1452     >>> doctest.DocTestRunner(verbose=False, optionflags=flags).run(test)
   1453     ... # doctest: +ELLIPSIS
   1454     **********************************************************************
   1455     File ..., line 5, in f
   1456     Failed example:
   1457         raise ValueError(2) # first failure
   1458     Exception raised:
   1459         ...
   1460         ValueError: 2
   1461     TestResults(failed=3, attempted=5)
   1462 
   1463 New option flags can also be registered, via register_optionflag().  Here
   1464 we reach into doctest's internals a bit.
   1465 
   1466     >>> unlikely = "UNLIKELY_OPTION_NAME"
   1467     >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
   1468     False
   1469     >>> new_flag_value = doctest.register_optionflag(unlikely)
   1470     >>> unlikely in doctest.OPTIONFLAGS_BY_NAME
   1471     True
   1472 
   1473 Before 2.4.4/2.5, registering a name more than once erroneously created
   1474 more than one flag value.  Here we verify that's fixed:
   1475 
   1476     >>> redundant_flag_value = doctest.register_optionflag(unlikely)
   1477     >>> redundant_flag_value == new_flag_value
   1478     True
   1479 
   1480 Clean up.
   1481     >>> del doctest.OPTIONFLAGS_BY_NAME[unlikely]
   1482 
   1483     """
   1484 
   1485     def option_directives(): r"""
   1486 Tests of `DocTestRunner`'s option directive mechanism.
   1487 
   1488 Option directives can be used to turn option flags on or off for a
   1489 single example.  To turn an option on for an example, follow that
   1490 example with a comment of the form ``# doctest: +OPTION``:
   1491 
   1492     >>> def f(x): r'''
   1493     ...     >>> print range(10)       # should fail: no ellipsis
   1494     ...     [0, 1, ..., 9]
   1495     ...
   1496     ...     >>> print range(10)       # doctest: +ELLIPSIS
   1497     ...     [0, 1, ..., 9]
   1498     ...     '''
   1499     >>> test = doctest.DocTestFinder().find(f)[0]
   1500     >>> doctest.DocTestRunner(verbose=False).run(test)
   1501     ... # doctest: +ELLIPSIS
   1502     **********************************************************************
   1503     File ..., line 2, in f
   1504     Failed example:
   1505         print range(10)       # should fail: no ellipsis
   1506     Expected:
   1507         [0, 1, ..., 9]
   1508     Got:
   1509         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   1510     TestResults(failed=1, attempted=2)
   1511 
   1512 To turn an option off for an example, follow that example with a
   1513 comment of the form ``# doctest: -OPTION``:
   1514 
   1515     >>> def f(x): r'''
   1516     ...     >>> print range(10)
   1517     ...     [0, 1, ..., 9]
   1518     ...
   1519     ...     >>> # should fail: no ellipsis
   1520     ...     >>> print range(10)       # doctest: -ELLIPSIS
   1521     ...     [0, 1, ..., 9]
   1522     ...     '''
   1523     >>> test = doctest.DocTestFinder().find(f)[0]
   1524     >>> doctest.DocTestRunner(verbose=False,
   1525     ...                       optionflags=doctest.ELLIPSIS).run(test)
   1526     ... # doctest: +ELLIPSIS
   1527     **********************************************************************
   1528     File ..., line 6, in f
   1529     Failed example:
   1530         print range(10)       # doctest: -ELLIPSIS
   1531     Expected:
   1532         [0, 1, ..., 9]
   1533     Got:
   1534         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   1535     TestResults(failed=1, attempted=2)
   1536 
   1537 Option directives affect only the example that they appear with; they
   1538 do not change the options for surrounding examples:
   1539 
   1540     >>> def f(x): r'''
   1541     ...     >>> print range(10)       # Should fail: no ellipsis
   1542     ...     [0, 1, ..., 9]
   1543     ...
   1544     ...     >>> print range(10)       # doctest: +ELLIPSIS
   1545     ...     [0, 1, ..., 9]
   1546     ...
   1547     ...     >>> print range(10)       # Should fail: no ellipsis
   1548     ...     [0, 1, ..., 9]
   1549     ...     '''
   1550     >>> test = doctest.DocTestFinder().find(f)[0]
   1551     >>> doctest.DocTestRunner(verbose=False).run(test)
   1552     ... # doctest: +ELLIPSIS
   1553     **********************************************************************
   1554     File ..., line 2, in f
   1555     Failed example:
   1556         print range(10)       # Should fail: no ellipsis
   1557     Expected:
   1558         [0, 1, ..., 9]
   1559     Got:
   1560         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   1561     **********************************************************************
   1562     File ..., line 8, in f
   1563     Failed example:
   1564         print range(10)       # Should fail: no ellipsis
   1565     Expected:
   1566         [0, 1, ..., 9]
   1567     Got:
   1568         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   1569     TestResults(failed=2, attempted=3)
   1570 
   1571 Multiple options may be modified by a single option directive.  They
   1572 may be separated by whitespace, commas, or both:
   1573 
   1574     >>> def f(x): r'''
   1575     ...     >>> print range(10)       # Should fail
   1576     ...     [0, 1,  ...,   9]
   1577     ...     >>> print range(10)       # Should succeed
   1578     ...     ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE
   1579     ...     [0, 1,  ...,   9]
   1580     ...     '''
   1581     >>> test = doctest.DocTestFinder().find(f)[0]
   1582     >>> doctest.DocTestRunner(verbose=False).run(test)
   1583     ... # doctest: +ELLIPSIS
   1584     **********************************************************************
   1585     File ..., line 2, in f
   1586     Failed example:
   1587         print range(10)       # Should fail
   1588     Expected:
   1589         [0, 1,  ...,   9]
   1590     Got:
   1591         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   1592     TestResults(failed=1, attempted=2)
   1593 
   1594     >>> def f(x): r'''
   1595     ...     >>> print range(10)       # Should fail
   1596     ...     [0, 1,  ...,   9]
   1597     ...     >>> print range(10)       # Should succeed
   1598     ...     ... # doctest: +ELLIPSIS,+NORMALIZE_WHITESPACE
   1599     ...     [0, 1,  ...,   9]
   1600     ...     '''
   1601     >>> test = doctest.DocTestFinder().find(f)[0]
   1602     >>> doctest.DocTestRunner(verbose=False).run(test)
   1603     ... # doctest: +ELLIPSIS
   1604     **********************************************************************
   1605     File ..., line 2, in f
   1606     Failed example:
   1607         print range(10)       # Should fail
   1608     Expected:
   1609         [0, 1,  ...,   9]
   1610     Got:
   1611         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   1612     TestResults(failed=1, attempted=2)
   1613 
   1614     >>> def f(x): r'''
   1615     ...     >>> print range(10)       # Should fail
   1616     ...     [0, 1,  ...,   9]
   1617     ...     >>> print range(10)       # Should succeed
   1618     ...     ... # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
   1619     ...     [0, 1,  ...,   9]
   1620     ...     '''
   1621     >>> test = doctest.DocTestFinder().find(f)[0]
   1622     >>> doctest.DocTestRunner(verbose=False).run(test)
   1623     ... # doctest: +ELLIPSIS
   1624     **********************************************************************
   1625     File ..., line 2, in f
   1626     Failed example:
   1627         print range(10)       # Should fail
   1628     Expected:
   1629         [0, 1,  ...,   9]
   1630     Got:
   1631         [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
   1632     TestResults(failed=1, attempted=2)
   1633 
   1634 The option directive may be put on the line following the source, as
   1635 long as a continuation prompt is used:
   1636 
   1637     >>> def f(x): r'''
   1638     ...     >>> print range(10)
   1639     ...     ... # doctest: +ELLIPSIS
   1640     ...     [0, 1, ..., 9]
   1641     ...     '''
   1642     >>> test = doctest.DocTestFinder().find(f)[0]
   1643     >>> doctest.DocTestRunner(verbose=False).run(test)
   1644     TestResults(failed=0, attempted=1)
   1645 
   1646 For examples with multi-line source, the option directive may appear
   1647 at the end of any line:
   1648 
   1649     >>> def f(x): r'''
   1650     ...     >>> for x in range(10): # doctest: +ELLIPSIS
   1651     ...     ...     print x,
   1652     ...     0 1 2 ... 9
   1653     ...
   1654     ...     >>> for x in range(10):
   1655     ...     ...     print x,        # doctest: +ELLIPSIS
   1656     ...     0 1 2 ... 9
   1657     ...     '''
   1658     >>> test = doctest.DocTestFinder().find(f)[0]
   1659     >>> doctest.DocTestRunner(verbose=False).run(test)
   1660     TestResults(failed=0, attempted=2)
   1661 
   1662 If more than one line of an example with multi-line source has an
   1663 option directive, then they are combined:
   1664 
   1665     >>> def f(x): r'''
   1666     ...     Should fail (option directive not on the last line):
   1667     ...         >>> for x in range(10): # doctest: +ELLIPSIS
   1668     ...         ...     print x,        # doctest: +NORMALIZE_WHITESPACE
   1669     ...         0  1    2...9
   1670     ...     '''
   1671     >>> test = doctest.DocTestFinder().find(f)[0]
   1672     >>> doctest.DocTestRunner(verbose=False).run(test)
   1673     TestResults(failed=0, attempted=1)
   1674 
   1675 It is an error to have a comment of the form ``# doctest:`` that is
   1676 *not* followed by words of the form ``+OPTION`` or ``-OPTION``, where
   1677 ``OPTION`` is an option that has been registered with
   1678 `register_option`:
   1679 
   1680     >>> # Error: Option not registered
   1681     >>> s = '>>> print 12   #doctest: +BADOPTION'
   1682     >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
   1683     Traceback (most recent call last):
   1684     ValueError: line 1 of the doctest for s has an invalid option: '+BADOPTION'
   1685 
   1686     >>> # Error: No + or - prefix
   1687     >>> s = '>>> print 12   #doctest: ELLIPSIS'
   1688     >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
   1689     Traceback (most recent call last):
   1690     ValueError: line 1 of the doctest for s has an invalid option: 'ELLIPSIS'
   1691 
   1692 It is an error to use an option directive on a line that contains no
   1693 source:
   1694 
   1695     >>> s = '>>> # doctest: +ELLIPSIS'
   1696     >>> test = doctest.DocTestParser().get_doctest(s, {}, 's', 's.py', 0)
   1697     Traceback (most recent call last):
   1698     ValueError: line 0 of the doctest for s has an option directive on a line with no example: '# doctest: +ELLIPSIS'
   1699 
   1700     """
   1701 
   1702     def test_unicode_output(self): r"""
   1703 
   1704 Check that unicode output works:
   1705 
   1706     >>> u'\xe9'
   1707     u'\xe9'
   1708 
   1709 If we return unicode, SpoofOut's buf variable becomes automagically
   1710 converted to unicode. This means all subsequent output becomes converted
   1711 to unicode, and if the output contains non-ascii characters that failed.
   1712 It used to be that this state change carried on between tests, meaning
   1713 tests would fail if unicode has been output previously in the testrun.
   1714 This test tests that this is no longer so:
   1715 
   1716     >>> print u'abc'
   1717     abc
   1718 
   1719 And then return a string with non-ascii characters:
   1720 
   1721     >>> print u'\xe9'.encode('utf-8')
   1722     
   1723 
   1724     """
   1725 
   1726 
   1727 def test_testsource(): r"""
   1728 Unit tests for `testsource()`.
   1729 
   1730 The testsource() function takes a module and a name, finds the (first)
   1731 test with that name in that module, and converts it to a script. The
   1732 example code is converted to regular Python code.  The surrounding
   1733 words and expected output are converted to comments:
   1734 
   1735     >>> import test.test_doctest
   1736     >>> name = 'test.test_doctest.sample_func'
   1737     >>> print doctest.testsource(test.test_doctest, name)
   1738     # Blah blah
   1739     #
   1740     print sample_func(22)
   1741     # Expected:
   1742     ## 44
   1743     #
   1744     # Yee ha!
   1745     <BLANKLINE>
   1746 
   1747     >>> name = 'test.test_doctest.SampleNewStyleClass'
   1748     >>> print doctest.testsource(test.test_doctest, name)
   1749     print '1\n2\n3'
   1750     # Expected:
   1751     ## 1
   1752     ## 2
   1753     ## 3
   1754     <BLANKLINE>
   1755 
   1756     >>> name = 'test.test_doctest.SampleClass.a_classmethod'
   1757     >>> print doctest.testsource(test.test_doctest, name)
   1758     print SampleClass.a_classmethod(10)
   1759     # Expected:
   1760     ## 12
   1761     print SampleClass(0).a_classmethod(10)
   1762     # Expected:
   1763     ## 12
   1764     <BLANKLINE>
   1765 """
   1766 
   1767 def test_debug(): r"""
   1768 
   1769 Create a docstring that we want to debug:
   1770 
   1771     >>> s = '''
   1772     ...     >>> x = 12
   1773     ...     >>> print x
   1774     ...     12
   1775     ...     '''
   1776 
   1777 Create some fake stdin input, to feed to the debugger:
   1778 
   1779     >>> import tempfile
   1780     >>> real_stdin = sys.stdin
   1781     >>> sys.stdin = _FakeInput(['next', 'print x', 'continue'])
   1782 
   1783 Run the debugger on the docstring, and then restore sys.stdin.
   1784 
   1785     >>> try: doctest.debug_src(s)
   1786     ... finally: sys.stdin = real_stdin
   1787     > <string>(1)<module>()
   1788     (Pdb) next
   1789     12
   1790     --Return--
   1791     > <string>(1)<module>()->None
   1792     (Pdb) print x
   1793     12
   1794     (Pdb) continue
   1795 
   1796 """
   1797 
   1798 def test_pdb_set_trace():
   1799     """Using pdb.set_trace from a doctest.
   1800 
   1801     You can use pdb.set_trace from a doctest.  To do so, you must
   1802     retrieve the set_trace function from the pdb module at the time
   1803     you use it.  The doctest module changes sys.stdout so that it can
   1804     capture program output.  It also temporarily replaces pdb.set_trace
   1805     with a version that restores stdout.  This is necessary for you to
   1806     see debugger output.
   1807 
   1808       >>> doc = '''
   1809       ... >>> x = 42
   1810       ... >>> raise Exception('cl')
   1811       ... Traceback (most recent call last):
   1812       ... Exception: cl
   1813       ... >>> import pdb; pdb.set_trace()
   1814       ... '''
   1815       >>> parser = doctest.DocTestParser()
   1816       >>> test = parser.get_doctest(doc, {}, "foo-br@baz", "foo-br@baz.py", 0)
   1817       >>> runner = doctest.DocTestRunner(verbose=False)
   1818 
   1819     To demonstrate this, we'll create a fake standard input that
   1820     captures our debugger input:
   1821 
   1822       >>> import tempfile
   1823       >>> real_stdin = sys.stdin
   1824       >>> sys.stdin = _FakeInput([
   1825       ...    'print x',  # print data defined by the example
   1826       ...    'continue', # stop debugging
   1827       ...    ''])
   1828 
   1829       >>> try: runner.run(test)
   1830       ... finally: sys.stdin = real_stdin
   1831       --Return--
   1832       > <doctest foo-br@baz[2]>(1)<module>()->None
   1833       -> import pdb; pdb.set_trace()
   1834       (Pdb) print x
   1835       42
   1836       (Pdb) continue
   1837       TestResults(failed=0, attempted=3)
   1838 
   1839       You can also put pdb.set_trace in a function called from a test:
   1840 
   1841       >>> def calls_set_trace():
   1842       ...    y=2
   1843       ...    import pdb; pdb.set_trace()
   1844 
   1845       >>> doc = '''
   1846       ... >>> x=1
   1847       ... >>> calls_set_trace()
   1848       ... '''
   1849       >>> test = parser.get_doctest(doc, globals(), "foo-br@baz", "foo-br@baz.py", 0)
   1850       >>> real_stdin = sys.stdin
   1851       >>> sys.stdin = _FakeInput([
   1852       ...    'print y',  # print data defined in the function
   1853       ...    'up',       # out of function
   1854       ...    'print x',  # print data defined by the example
   1855       ...    'continue', # stop debugging
   1856       ...    ''])
   1857 
   1858       >>> try:
   1859       ...     runner.run(test)
   1860       ... finally:
   1861       ...     sys.stdin = real_stdin
   1862       --Return--
   1863       > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
   1864       -> import pdb; pdb.set_trace()
   1865       (Pdb) print y
   1866       2
   1867       (Pdb) up
   1868       > <doctest foo-br@baz[1]>(1)<module>()
   1869       -> calls_set_trace()
   1870       (Pdb) print x
   1871       1
   1872       (Pdb) continue
   1873       TestResults(failed=0, attempted=2)
   1874 
   1875     During interactive debugging, source code is shown, even for
   1876     doctest examples:
   1877 
   1878       >>> doc = '''
   1879       ... >>> def f(x):
   1880       ... ...     g(x*2)
   1881       ... >>> def g(x):
   1882       ... ...     print x+3
   1883       ... ...     import pdb; pdb.set_trace()
   1884       ... >>> f(3)
   1885       ... '''
   1886       >>> test = parser.get_doctest(doc, globals(), "foo-br@baz", "foo-br@baz.py", 0)
   1887       >>> real_stdin = sys.stdin
   1888       >>> sys.stdin = _FakeInput([
   1889       ...    'list',     # list source from example 2
   1890       ...    'next',     # return from g()
   1891       ...    'list',     # list source from example 1
   1892       ...    'next',     # return from f()
   1893       ...    'list',     # list source from example 3
   1894       ...    'continue', # stop debugging
   1895       ...    ''])
   1896       >>> try: runner.run(test)
   1897       ... finally: sys.stdin = real_stdin
   1898       ... # doctest: +NORMALIZE_WHITESPACE
   1899       --Return--
   1900       > <doctest foo-br@baz[1]>(3)g()->None
   1901       -> import pdb; pdb.set_trace()
   1902       (Pdb) list
   1903         1     def g(x):
   1904         2         print x+3
   1905         3  ->     import pdb; pdb.set_trace()
   1906       [EOF]
   1907       (Pdb) next
   1908       --Return--
   1909       > <doctest foo-br@baz[0]>(2)f()->None
   1910       -> g(x*2)
   1911       (Pdb) list
   1912         1     def f(x):
   1913         2  ->     g(x*2)
   1914       [EOF]
   1915       (Pdb) next
   1916       --Return--
   1917       > <doctest foo-br@baz[2]>(1)<module>()->None
   1918       -> f(3)
   1919       (Pdb) list
   1920         1  -> f(3)
   1921       [EOF]
   1922       (Pdb) continue
   1923       **********************************************************************
   1924       File "foo-br@baz.py", line 7, in foo-br@baz
   1925       Failed example:
   1926           f(3)
   1927       Expected nothing
   1928       Got:
   1929           9
   1930       TestResults(failed=1, attempted=3)
   1931       """
   1932 
   1933 def test_pdb_set_trace_nested():
   1934     """This illustrates more-demanding use of set_trace with nested functions.
   1935 
   1936     >>> class C(object):
   1937     ...     def calls_set_trace(self):
   1938     ...         y = 1
   1939     ...         import pdb; pdb.set_trace()
   1940     ...         self.f1()
   1941     ...         y = 2
   1942     ...     def f1(self):
   1943     ...         x = 1
   1944     ...         self.f2()
   1945     ...         x = 2
   1946     ...     def f2(self):
   1947     ...         z = 1
   1948     ...         z = 2
   1949 
   1950     >>> calls_set_trace = C().calls_set_trace
   1951 
   1952     >>> doc = '''
   1953     ... >>> a = 1
   1954     ... >>> calls_set_trace()
   1955     ... '''
   1956     >>> parser = doctest.DocTestParser()
   1957     >>> runner = doctest.DocTestRunner(verbose=False)
   1958     >>> test = parser.get_doctest(doc, globals(), "foo-br@baz", "foo-br@baz.py", 0)
   1959     >>> real_stdin = sys.stdin
   1960     >>> sys.stdin = _FakeInput([
   1961     ...    'print y',  # print data defined in the function
   1962     ...    'step', 'step', 'step', 'step', 'step', 'step', 'print z',
   1963     ...    'up', 'print x',
   1964     ...    'up', 'print y',
   1965     ...    'up', 'print foo',
   1966     ...    'continue', # stop debugging
   1967     ...    ''])
   1968 
   1969     >>> try:
   1970     ...     runner.run(test)
   1971     ... finally:
   1972     ...     sys.stdin = real_stdin
   1973     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
   1974     -> self.f1()
   1975     (Pdb) print y
   1976     1
   1977     (Pdb) step
   1978     --Call--
   1979     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
   1980     -> def f1(self):
   1981     (Pdb) step
   1982     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
   1983     -> x = 1
   1984     (Pdb) step
   1985     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
   1986     -> self.f2()
   1987     (Pdb) step
   1988     --Call--
   1989     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
   1990     -> def f2(self):
   1991     (Pdb) step
   1992     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
   1993     -> z = 1
   1994     (Pdb) step
   1995     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
   1996     -> z = 2
   1997     (Pdb) print z
   1998     1
   1999     (Pdb) up
   2000     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
   2001     -> self.f2()
   2002     (Pdb) print x
   2003     1
   2004     (Pdb) up
   2005     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
   2006     -> self.f1()
   2007     (Pdb) print y
   2008     1
   2009     (Pdb) up
   2010     > <doctest foo-br@baz[1]>(1)<module>()
   2011     -> calls_set_trace()
   2012     (Pdb) print foo
   2013     *** NameError: name 'foo' is not defined
   2014     (Pdb) continue
   2015     TestResults(failed=0, attempted=2)
   2016 """
   2017 
   2018 def test_DocTestSuite():
   2019     """DocTestSuite creates a unittest test suite from a doctest.
   2020 
   2021        We create a Suite by providing a module.  A module can be provided
   2022        by passing a module object:
   2023 
   2024          >>> import unittest
   2025          >>> import test.sample_doctest
   2026          >>> suite = doctest.DocTestSuite(test.sample_doctest)
   2027          >>> suite.run(unittest.TestResult())
   2028          <unittest.result.TestResult run=9 errors=0 failures=4>
   2029 
   2030        We can also supply the module by name:
   2031 
   2032          >>> suite = doctest.DocTestSuite('test.sample_doctest')
   2033          >>> suite.run(unittest.TestResult())
   2034          <unittest.result.TestResult run=9 errors=0 failures=4>
   2035 
   2036        The module need not contain any doctest examples:
   2037 
   2038          >>> suite = doctest.DocTestSuite('test.sample_doctest_no_doctests')
   2039          >>> suite.run(unittest.TestResult())
   2040          <unittest.result.TestResult run=0 errors=0 failures=0>
   2041 
   2042        However, if DocTestSuite finds no docstrings, it raises an error:
   2043 
   2044          >>> try:
   2045          ...     doctest.DocTestSuite('test.sample_doctest_no_docstrings')
   2046          ... except ValueError as e:
   2047          ...     error = e
   2048 
   2049          >>> print(error.args[1])
   2050          has no docstrings
   2051 
   2052        You can prevent this error by passing a DocTestFinder instance with
   2053        the `exclude_empty` keyword argument set to False:
   2054 
   2055          >>> finder = doctest.DocTestFinder(exclude_empty=False)
   2056          >>> suite = doctest.DocTestSuite('test.sample_doctest_no_docstrings',
   2057          ...                              test_finder=finder)
   2058          >>> suite.run(unittest.TestResult())
   2059          <unittest.result.TestResult run=0 errors=0 failures=0>
   2060 
   2061        We can use the current module:
   2062 
   2063          >>> suite = test.sample_doctest.test_suite()
   2064          >>> suite.run(unittest.TestResult())
   2065          <unittest.result.TestResult run=9 errors=0 failures=4>
   2066 
   2067        We can supply global variables.  If we pass globs, they will be
   2068        used instead of the module globals.  Here we'll pass an empty
   2069        globals, triggering an extra error:
   2070 
   2071          >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
   2072          >>> suite.run(unittest.TestResult())
   2073          <unittest.result.TestResult run=9 errors=0 failures=5>
   2074 
   2075        Alternatively, we can provide extra globals.  Here we'll make an
   2076        error go away by providing an extra global variable:
   2077 
   2078          >>> suite = doctest.DocTestSuite('test.sample_doctest',
   2079          ...                              extraglobs={'y': 1})
   2080          >>> suite.run(unittest.TestResult())
   2081          <unittest.result.TestResult run=9 errors=0 failures=3>
   2082 
   2083        You can pass option flags.  Here we'll cause an extra error
   2084        by disabling the blank-line feature:
   2085 
   2086          >>> suite = doctest.DocTestSuite('test.sample_doctest',
   2087          ...                      optionflags=doctest.DONT_ACCEPT_BLANKLINE)
   2088          >>> suite.run(unittest.TestResult())
   2089          <unittest.result.TestResult run=9 errors=0 failures=5>
   2090 
   2091        You can supply setUp and tearDown functions:
   2092 
   2093          >>> def setUp(t):
   2094          ...     import test.test_doctest
   2095          ...     test.test_doctest.sillySetup = True
   2096 
   2097          >>> def tearDown(t):
   2098          ...     import test.test_doctest
   2099          ...     del test.test_doctest.sillySetup
   2100 
   2101        Here, we installed a silly variable that the test expects:
   2102 
   2103          >>> suite = doctest.DocTestSuite('test.sample_doctest',
   2104          ...      setUp=setUp, tearDown=tearDown)
   2105          >>> suite.run(unittest.TestResult())
   2106          <unittest.result.TestResult run=9 errors=0 failures=3>
   2107 
   2108        But the tearDown restores sanity:
   2109 
   2110          >>> import test.test_doctest
   2111          >>> test.test_doctest.sillySetup
   2112          Traceback (most recent call last):
   2113          ...
   2114          AttributeError: 'module' object has no attribute 'sillySetup'
   2115 
   2116        The setUp and tearDown functions are passed test objects. Here
   2117        we'll use the setUp function to supply the missing variable y:
   2118 
   2119          >>> def setUp(test):
   2120          ...     test.globs['y'] = 1
   2121 
   2122          >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
   2123          >>> suite.run(unittest.TestResult())
   2124          <unittest.result.TestResult run=9 errors=0 failures=3>
   2125 
   2126        Here, we didn't need to use a tearDown function because we
   2127        modified the test globals, which are a copy of the
   2128        sample_doctest module dictionary.  The test globals are
   2129        automatically cleared for us after a test.
   2130        """
   2131 
   2132 def test_DocFileSuite():
   2133     """We can test tests found in text files using a DocFileSuite.
   2134 
   2135        We create a suite by providing the names of one or more text
   2136        files that include examples:
   2137 
   2138          >>> import unittest
   2139          >>> suite = doctest.DocFileSuite('test_doctest.txt',
   2140          ...                              'test_doctest2.txt',
   2141          ...                              'test_doctest4.txt')
   2142          >>> suite.run(unittest.TestResult())
   2143          <unittest.result.TestResult run=3 errors=0 failures=3>
   2144 
   2145        The test files are looked for in the directory containing the
   2146        calling module.  A package keyword argument can be provided to
   2147        specify a different relative location.
   2148 
   2149          >>> import unittest
   2150          >>> suite = doctest.DocFileSuite('test_doctest.txt',
   2151          ...                              'test_doctest2.txt',
   2152          ...                              'test_doctest4.txt',
   2153          ...                              package='test')
   2154          >>> suite.run(unittest.TestResult())
   2155          <unittest.result.TestResult run=3 errors=0 failures=3>
   2156 
   2157        Support for using a package's __loader__.get_data() is also
   2158        provided.
   2159 
   2160          >>> import unittest, pkgutil, test
   2161          >>> added_loader = False
   2162          >>> if not hasattr(test, '__loader__'):
   2163          ...     test.__loader__ = pkgutil.get_loader(test)
   2164          ...     added_loader = True
   2165          >>> try:
   2166          ...     suite = doctest.DocFileSuite('test_doctest.txt',
   2167          ...                                  'test_doctest2.txt',
   2168          ...                                  'test_doctest4.txt',
   2169          ...                                  package='test')
   2170          ...     suite.run(unittest.TestResult())
   2171          ... finally:
   2172          ...     if added_loader:
   2173          ...         del test.__loader__
   2174          <unittest.result.TestResult run=3 errors=0 failures=3>
   2175 
   2176        '/' should be used as a path separator.  It will be converted
   2177        to a native separator at run time:
   2178 
   2179          >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
   2180          >>> suite.run(unittest.TestResult())
   2181          <unittest.result.TestResult run=1 errors=0 failures=1>
   2182 
   2183        If DocFileSuite is used from an interactive session, then files
   2184        are resolved relative to the directory of sys.argv[0]:
   2185 
   2186          >>> import types, os.path, test.test_doctest
   2187          >>> save_argv = sys.argv
   2188          >>> sys.argv = [test.test_doctest.__file__]
   2189          >>> suite = doctest.DocFileSuite('test_doctest.txt',
   2190          ...                              package=types.ModuleType('__main__'))
   2191          >>> sys.argv = save_argv
   2192 
   2193        By setting `module_relative=False`, os-specific paths may be
   2194        used (including absolute paths and paths relative to the
   2195        working directory):
   2196 
   2197          >>> # Get the absolute path of the test package.
   2198          >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
   2199          >>> test_pkg_path = os.path.split(test_doctest_path)[0]
   2200 
   2201          >>> # Use it to find the absolute path of test_doctest.txt.
   2202          >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
   2203 
   2204          >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
   2205          >>> suite.run(unittest.TestResult())
   2206          <unittest.result.TestResult run=1 errors=0 failures=1>
   2207 
   2208        It is an error to specify `package` when `module_relative=False`:
   2209 
   2210          >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
   2211          ...                              package='test')
   2212          Traceback (most recent call last):
   2213          ValueError: Package may only be specified for module-relative paths.
   2214 
   2215        You can specify initial global variables:
   2216 
   2217          >>> suite = doctest.DocFileSuite('test_doctest.txt',
   2218          ...                              'test_doctest2.txt',
   2219          ...                              'test_doctest4.txt',
   2220          ...                              globs={'favorite_color': 'blue'})
   2221          >>> suite.run(unittest.TestResult())
   2222          <unittest.result.TestResult run=3 errors=0 failures=2>
   2223 
   2224        In this case, we supplied a missing favorite color. You can
   2225        provide doctest options:
   2226 
   2227          >>> suite = doctest.DocFileSuite('test_doctest.txt',
   2228          ...                              'test_doctest2.txt',
   2229          ...                              'test_doctest4.txt',
   2230          ...                         optionflags=doctest.DONT_ACCEPT_BLANKLINE,
   2231          ...                              globs={'favorite_color': 'blue'})
   2232          >>> suite.run(unittest.TestResult())
   2233          <unittest.result.TestResult run=3 errors=0 failures=3>
   2234 
   2235        And, you can provide setUp and tearDown functions:
   2236 
   2237          >>> def setUp(t):
   2238          ...     import test.test_doctest
   2239          ...     test.test_doctest.sillySetup = True
   2240 
   2241          >>> def tearDown(t):
   2242          ...     import test.test_doctest
   2243          ...     del test.test_doctest.sillySetup
   2244 
   2245        Here, we installed a silly variable that the test expects:
   2246 
   2247          >>> suite = doctest.DocFileSuite('test_doctest.txt',
   2248          ...                              'test_doctest2.txt',
   2249          ...                              'test_doctest4.txt',
   2250          ...                              setUp=setUp, tearDown=tearDown)
   2251          >>> suite.run(unittest.TestResult())
   2252          <unittest.result.TestResult run=3 errors=0 failures=2>
   2253 
   2254        But the tearDown restores sanity:
   2255 
   2256          >>> import test.test_doctest
   2257          >>> test.test_doctest.sillySetup
   2258          Traceback (most recent call last):
   2259          ...
   2260          AttributeError: 'module' object has no attribute 'sillySetup'
   2261 
   2262        The setUp and tearDown functions are passed test objects.
   2263        Here, we'll use a setUp function to set the favorite color in
   2264        test_doctest.txt:
   2265 
   2266          >>> def setUp(test):
   2267          ...     test.globs['favorite_color'] = 'blue'
   2268 
   2269          >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
   2270          >>> suite.run(unittest.TestResult())
   2271          <unittest.result.TestResult run=1 errors=0 failures=0>
   2272 
   2273        Here, we didn't need to use a tearDown function because we
   2274        modified the test globals.  The test globals are
   2275        automatically cleared for us after a test.
   2276 
   2277        Tests in a file run using `DocFileSuite` can also access the
   2278        `__file__` global, which is set to the name of the file
   2279        containing the tests:
   2280 
   2281          >>> suite = doctest.DocFileSuite('test_doctest3.txt')
   2282          >>> suite.run(unittest.TestResult())
   2283          <unittest.result.TestResult run=1 errors=0 failures=0>
   2284 
   2285        If the tests contain non-ASCII characters, we have to specify which
   2286        encoding the file is encoded with. We do so by using the `encoding`
   2287        parameter:
   2288 
   2289          >>> suite = doctest.DocFileSuite('test_doctest.txt',
   2290          ...                              'test_doctest2.txt',
   2291          ...                              'test_doctest4.txt',
   2292          ...                              encoding='utf-8')
   2293          >>> suite.run(unittest.TestResult())
   2294          <unittest.result.TestResult run=3 errors=0 failures=2>
   2295 
   2296        """
   2297 
   2298 def test_trailing_space_in_test():
   2299     """
   2300     Trailing spaces in expected output are significant:
   2301 
   2302       >>> x, y = 'foo', ''
   2303       >>> print x, y
   2304       foo \n
   2305     """
   2306 
   2307 
   2308 def test_unittest_reportflags():
   2309     """Default unittest reporting flags can be set to control reporting
   2310 
   2311     Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
   2312     only the first failure of each test.  First, we'll look at the
   2313     output without the flag.  The file test_doctest.txt file has two
   2314     tests. They both fail if blank lines are disabled:
   2315 
   2316       >>> suite = doctest.DocFileSuite('test_doctest.txt',
   2317       ...                          optionflags=doctest.DONT_ACCEPT_BLANKLINE)
   2318       >>> import unittest
   2319       >>> result = suite.run(unittest.TestResult())
   2320       >>> print result.failures[0][1] # doctest: +ELLIPSIS
   2321       Traceback ...
   2322       Failed example:
   2323           favorite_color
   2324       ...
   2325       Failed example:
   2326           if 1:
   2327       ...
   2328 
   2329     Note that we see both failures displayed.
   2330 
   2331       >>> old = doctest.set_unittest_reportflags(
   2332       ...    doctest.REPORT_ONLY_FIRST_FAILURE)
   2333 
   2334     Now, when we run the test:
   2335 
   2336       >>> result = suite.run(unittest.TestResult())
   2337       >>> print result.failures[0][1] # doctest: +ELLIPSIS
   2338       Traceback ...
   2339       Failed example:
   2340           favorite_color
   2341       Exception raised:
   2342           ...
   2343           NameError: name 'favorite_color' is not defined
   2344       <BLANKLINE>
   2345       <BLANKLINE>
   2346 
   2347     We get only the first failure.
   2348 
   2349     If we give any reporting options when we set up the tests,
   2350     however:
   2351 
   2352       >>> suite = doctest.DocFileSuite('test_doctest.txt',
   2353       ...     optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
   2354 
   2355     Then the default eporting options are ignored:
   2356 
   2357       >>> result = suite.run(unittest.TestResult())
   2358       >>> print result.failures[0][1] # doctest: +ELLIPSIS
   2359       Traceback ...
   2360       Failed example:
   2361           favorite_color
   2362       ...
   2363       Failed example:
   2364           if 1:
   2365              print 'a'
   2366              print
   2367              print 'b'
   2368       Differences (ndiff with -expected +actual):
   2369             a
   2370           - <BLANKLINE>
   2371           +
   2372             b
   2373       <BLANKLINE>
   2374       <BLANKLINE>
   2375 
   2376 
   2377     Test runners can restore the formatting flags after they run:
   2378 
   2379       >>> ignored = doctest.set_unittest_reportflags(old)
   2380 
   2381     """
   2382 
   2383 def test_testfile(): r"""
   2384 Tests for the `testfile()` function.  This function runs all the
   2385 doctest examples in a given file.  In its simple invokation, it is
   2386 called with the name of a file, which is taken to be relative to the
   2387 calling module.  The return value is (#failures, #tests).
   2388 
   2389 We don't want `-v` in sys.argv for these tests.
   2390 
   2391     >>> save_argv = sys.argv
   2392     >>> if '-v' in sys.argv:
   2393     ...     sys.argv = [arg for arg in save_argv if arg != '-v']
   2394 
   2395 
   2396     >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
   2397     **********************************************************************
   2398     File "...", line 6, in test_doctest.txt
   2399     Failed example:
   2400         favorite_color
   2401     Exception raised:
   2402         ...
   2403         NameError: name 'favorite_color' is not defined
   2404     **********************************************************************
   2405     1 items had failures:
   2406        1 of   2 in test_doctest.txt
   2407     ***Test Failed*** 1 failures.
   2408     TestResults(failed=1, attempted=2)
   2409     >>> doctest.master = None  # Reset master.
   2410 
   2411 (Note: we'll be clearing doctest.master after each call to
   2412 `doctest.testfile`, to suppress warnings about multiple tests with the
   2413 same name.)
   2414 
   2415 Globals may be specified with the `globs` and `extraglobs` parameters:
   2416 
   2417     >>> globs = {'favorite_color': 'blue'}
   2418     >>> doctest.testfile('test_doctest.txt', globs=globs)
   2419     TestResults(failed=0, attempted=2)
   2420     >>> doctest.master = None  # Reset master.
   2421 
   2422     >>> extraglobs = {'favorite_color': 'red'}
   2423     >>> doctest.testfile('test_doctest.txt', globs=globs,
   2424     ...                  extraglobs=extraglobs) # doctest: +ELLIPSIS
   2425     **********************************************************************
   2426     File "...", line 6, in test_doctest.txt
   2427     Failed example:
   2428         favorite_color
   2429     Expected:
   2430         'blue'
   2431     Got:
   2432         'red'
   2433     **********************************************************************
   2434     1 items had failures:
   2435        1 of   2 in test_doctest.txt
   2436     ***Test Failed*** 1 failures.
   2437     TestResults(failed=1, attempted=2)
   2438     >>> doctest.master = None  # Reset master.
   2439 
   2440 The file may be made relative to a given module or package, using the
   2441 optional `module_relative` parameter:
   2442 
   2443     >>> doctest.testfile('test_doctest.txt', globs=globs,
   2444     ...                  module_relative='test')
   2445     TestResults(failed=0, attempted=2)
   2446     >>> doctest.master = None  # Reset master.
   2447 
   2448 Verbosity can be increased with the optional `verbose` parameter:
   2449 
   2450     >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
   2451     Trying:
   2452         favorite_color
   2453     Expecting:
   2454         'blue'
   2455     ok
   2456     Trying:
   2457         if 1:
   2458            print 'a'
   2459            print
   2460            print 'b'
   2461     Expecting:
   2462         a
   2463         <BLANKLINE>
   2464         b
   2465     ok
   2466     1 items passed all tests:
   2467        2 tests in test_doctest.txt
   2468     2 tests in 1 items.
   2469     2 passed and 0 failed.
   2470     Test passed.
   2471     TestResults(failed=0, attempted=2)
   2472     >>> doctest.master = None  # Reset master.
   2473 
   2474 The name of the test may be specified with the optional `name`
   2475 parameter:
   2476 
   2477     >>> doctest.testfile('test_doctest.txt', name='newname')
   2478     ... # doctest: +ELLIPSIS
   2479     **********************************************************************
   2480     File "...", line 6, in newname
   2481     ...
   2482     TestResults(failed=1, attempted=2)
   2483     >>> doctest.master = None  # Reset master.
   2484 
   2485 The summary report may be suppressed with the optional `report`
   2486 parameter:
   2487 
   2488     >>> doctest.testfile('test_doctest.txt', report=False)
   2489     ... # doctest: +ELLIPSIS
   2490     **********************************************************************
   2491     File "...", line 6, in test_doctest.txt
   2492     Failed example:
   2493         favorite_color
   2494     Exception raised:
   2495         ...
   2496         NameError: name 'favorite_color' is not defined
   2497     TestResults(failed=1, attempted=2)
   2498     >>> doctest.master = None  # Reset master.
   2499 
   2500 The optional keyword argument `raise_on_error` can be used to raise an
   2501 exception on the first error (which may be useful for postmortem
   2502 debugging):
   2503 
   2504     >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
   2505     ... # doctest: +ELLIPSIS
   2506     Traceback (most recent call last):
   2507     UnexpectedException: ...
   2508     >>> doctest.master = None  # Reset master.
   2509 
   2510 If the tests contain non-ASCII characters, the tests might fail, since
   2511 it's unknown which encoding is used. The encoding can be specified
   2512 using the optional keyword argument `encoding`:
   2513 
   2514     >>> doctest.testfile('test_doctest4.txt') # doctest: +ELLIPSIS
   2515     **********************************************************************
   2516     File "...", line 7, in test_doctest4.txt
   2517     Failed example:
   2518         u'...'
   2519     Expected:
   2520         u'f\xf6\xf6'
   2521     Got:
   2522         u'f\xc3\xb6\xc3\xb6'
   2523     **********************************************************************
   2524     ...
   2525     **********************************************************************
   2526     1 items had failures:
   2527        2 of   4 in test_doctest4.txt
   2528     ***Test Failed*** 2 failures.
   2529     TestResults(failed=2, attempted=4)
   2530     >>> doctest.master = None  # Reset master.
   2531 
   2532     >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
   2533     TestResults(failed=0, attempted=4)
   2534     >>> doctest.master = None  # Reset master.
   2535 
   2536 Switch the module encoding to 'utf-8' to test the verbose output without
   2537 bothering with the current sys.stdout encoding.
   2538 
   2539     >>> doctest._encoding, saved_encoding = 'utf-8', doctest._encoding
   2540     >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
   2541     Trying:
   2542         u'f'
   2543     Expecting:
   2544         u'f\xf6\xf6'
   2545     ok
   2546     Trying:
   2547         u'br'
   2548     Expecting:
   2549         u'b\u0105r'
   2550     ok
   2551     Trying:
   2552         'f'
   2553     Expecting:
   2554         'f\xc3\xb6\xc3\xb6'
   2555     ok
   2556     Trying:
   2557         'br'
   2558     Expecting:
   2559         'b\xc4\x85r'
   2560     ok
   2561     1 items passed all tests:
   2562        4 tests in test_doctest4.txt
   2563     4 tests in 1 items.
   2564     4 passed and 0 failed.
   2565     Test passed.
   2566     TestResults(failed=0, attempted=4)
   2567     >>> doctest._encoding = saved_encoding
   2568     >>> doctest.master = None  # Reset master.
   2569     >>> sys.argv = save_argv
   2570 """
   2571 
   2572 def test_lineendings(): r"""
   2573 *nix systems use \n line endings, while Windows systems use \r\n.  Python
   2574 handles this using universal newline mode for reading files.  Let's make
   2575 sure doctest does so (issue 8473) by creating temporary test files using each
   2576 of the two line disciplines.  One of the two will be the "wrong" one for the
   2577 platform the test is run on.
   2578 
   2579 Windows line endings first:
   2580 
   2581     >>> import tempfile, os
   2582     >>> fn = tempfile.mktemp()
   2583     >>> with open(fn, 'wb') as f:
   2584     ...     f.write('Test:\r\n\r\n  >>> x = 1 + 1\r\n\r\nDone.\r\n')
   2585     >>> doctest.testfile(fn, module_relative=False, verbose=False)
   2586     TestResults(failed=0, attempted=1)
   2587     >>> os.remove(fn)
   2588 
   2589 And now *nix line endings:
   2590 
   2591     >>> fn = tempfile.mktemp()
   2592     >>> with open(fn, 'wb') as f:
   2593     ...     f.write('Test:\n\n  >>> x = 1 + 1\n\nDone.\n')
   2594     >>> doctest.testfile(fn, module_relative=False, verbose=False)
   2595     TestResults(failed=0, attempted=1)
   2596     >>> os.remove(fn)
   2597 
   2598 """
   2599 
   2600 # old_test1, ... used to live in doctest.py, but cluttered it.  Note
   2601 # that these use the deprecated doctest.Tester, so should go away (or
   2602 # be rewritten) someday.
   2603 
   2604 def old_test1(): r"""
   2605 >>> from doctest import Tester
   2606 >>> t = Tester(globs={'x': 42}, verbose=0)
   2607 >>> t.runstring(r'''
   2608 ...      >>> x = x * 2
   2609 ...      >>> print x
   2610 ...      42
   2611 ... ''', 'XYZ')
   2612 **********************************************************************
   2613 Line 3, in XYZ
   2614 Failed example:
   2615     print x
   2616 Expected:
   2617     42
   2618 Got:
   2619     84
   2620 TestResults(failed=1, attempted=2)
   2621 >>> t.runstring(">>> x = x * 2\n>>> print x\n84\n", 'example2')
   2622 TestResults(failed=0, attempted=2)
   2623 >>> t.summarize()
   2624 **********************************************************************
   2625 1 items had failures:
   2626    1 of   2 in XYZ
   2627 ***Test Failed*** 1 failures.
   2628 TestResults(failed=1, attempted=4)
   2629 >>> t.summarize(verbose=1)
   2630 1 items passed all tests:
   2631    2 tests in example2
   2632 **********************************************************************
   2633 1 items had failures:
   2634    1 of   2 in XYZ
   2635 4 tests in 2 items.
   2636 3 passed and 1 failed.
   2637 ***Test Failed*** 1 failures.
   2638 TestResults(failed=1, attempted=4)
   2639 """
   2640 
   2641 def old_test2(): r"""
   2642         >>> from doctest import Tester
   2643         >>> t = Tester(globs={}, verbose=1)
   2644         >>> test = r'''
   2645         ...    # just an example
   2646         ...    >>> x = 1 + 2
   2647         ...    >>> x
   2648         ...    3
   2649         ... '''
   2650         >>> t.runstring(test, "Example")
   2651         Running string Example
   2652         Trying:
   2653             x = 1 + 2
   2654         Expecting nothing
   2655         ok
   2656         Trying:
   2657             x
   2658         Expecting:
   2659             3
   2660         ok
   2661         0 of 2 examples failed in string Example
   2662         TestResults(failed=0, attempted=2)
   2663 """
   2664 
   2665 def old_test3(): r"""
   2666         >>> from doctest import Tester
   2667         >>> t = Tester(globs={}, verbose=0)
   2668         >>> def _f():
   2669         ...     '''Trivial docstring example.
   2670         ...     >>> assert 2 == 2
   2671         ...     '''
   2672         ...     return 32
   2673         ...
   2674         >>> t.rundoc(_f)  # expect 0 failures in 1 example
   2675         TestResults(failed=0, attempted=1)
   2676 """
   2677 
   2678 def old_test4(): """
   2679         >>> import types
   2680         >>> m1 = types.ModuleType('_m1')
   2681         >>> m2 = types.ModuleType('_m2')
   2682         >>> test_data = \"""
   2683         ... def _f():
   2684         ...     '''>>> assert 1 == 1
   2685         ...     '''
   2686         ... def g():
   2687         ...    '''>>> assert 2 != 1
   2688         ...    '''
   2689         ... class H:
   2690         ...    '''>>> assert 2 > 1
   2691         ...    '''
   2692         ...    def bar(self):
   2693         ...        '''>>> assert 1 < 2
   2694         ...        '''
   2695         ... \"""
   2696         >>> exec test_data in m1.__dict__
   2697         >>> exec test_data in m2.__dict__
   2698         >>> m1.__dict__.update({"f2": m2._f, "g2": m2.g, "h2": m2.H})
   2699 
   2700         Tests that objects outside m1 are excluded:
   2701 
   2702         >>> from doctest import Tester
   2703         >>> t = Tester(globs={}, verbose=0)
   2704         >>> t.rundict(m1.__dict__, "rundict_test", m1)  # f2 and g2 and h2 skipped
   2705         TestResults(failed=0, attempted=4)
   2706 
   2707         Once more, not excluding stuff outside m1:
   2708 
   2709         >>> t = Tester(globs={}, verbose=0)
   2710         >>> t.rundict(m1.__dict__, "rundict_test_pvt")  # None are skipped.
   2711         TestResults(failed=0, attempted=8)
   2712 
   2713         The exclusion of objects from outside the designated module is
   2714         meant to be invoked automagically by testmod.
   2715 
   2716         >>> doctest.testmod(m1, verbose=False)
   2717         TestResults(failed=0, attempted=4)
   2718 """
   2719 
   2720 ######################################################################
   2721 ## Main
   2722 ######################################################################
   2723 
   2724 def test_main():
   2725     # Check the doctest cases in doctest itself:
   2726     test_support.run_doctest(doctest, verbosity=True)
   2727 
   2728     from test import test_doctest
   2729 
   2730     # Ignore all warnings about the use of class Tester in this module.
   2731     deprecations = []
   2732     if __debug__:
   2733         deprecations.append(("class Tester is deprecated", DeprecationWarning))
   2734     if sys.py3kwarning:
   2735         deprecations += [("backquote not supported", SyntaxWarning),
   2736                          ("execfile.. not supported", DeprecationWarning)]
   2737     with test_support.check_warnings(*deprecations):
   2738         # Check the doctest cases defined here:
   2739         test_support.run_doctest(test_doctest, verbosity=True)
   2740 
   2741 import sys
   2742 def test_coverage(coverdir):
   2743     trace = test_support.import_module('trace')
   2744     tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
   2745                          trace=0, count=1)
   2746     tracer.run('reload(doctest); test_main()')
   2747     r = tracer.results()
   2748     print 'Writing coverage results...'
   2749     r.write_results(show_missing=True, summary=True,
   2750                     coverdir=coverdir)
   2751 
   2752 if __name__ == '__main__':
   2753     if '-c' in sys.argv:
   2754         test_coverage('/tmp/doctest.cover')
   2755     else:
   2756         test_main()
   2757