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