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