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