Back to index

python3.2  3.2.2
Classes | Functions
test.test_doctest Namespace Reference

Classes

class  SampleClass
class  SampleNewStyleClass
class  _FakeInput
 Fake stdin (for testing interactive debugging) More...
class  test_DocTestRunner

Functions

def sample_func
 Sample Objects (used by test cases)
def test_Example
 Test Cases.
def test_DocTest
def test_DocTestFinder
def test_DocTestParser
def test_testsource
def test_debug
def test_pdb_set_trace
def test_pdb_set_trace_nested
def test_DocTestSuite
def test_DocFileSuite
def test_trailing_space_in_test
def test_unittest_reportflags
def test_testfile
def test_testmod
def test_unicode
def test_main
 Main.
def test_coverage

Detailed Description

Test script for doctest.

Function Documentation

Sample Objects (used by test cases)

Blah blah

>>> print(sample_func(22))
44

Yee ha!

Definition at line 17 of file test_doctest.py.

00017 
00018 def sample_func(v):
00019     """
00020     Blah blah
00021 
00022     >>> print(sample_func(22))
00023     44
00024 
00025     Yee ha!
00026     """
00027     return v+v

def test.test_doctest.test_coverage (   coverdir)

Definition at line 2483 of file test_doctest.py.

02483 
02484 def test_coverage(coverdir):
02485     trace = support.import_module('trace')
02486     tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
02487                          trace=0, count=1)
02488     tracer.run('test_main()')
02489     r = tracer.results()
02490     print('Writing coverage results...')
02491     r.write_results(show_missing=True, summary=True,
02492                     coverdir=coverdir)

Here is the call graph for this function:

Definition at line 1659 of file test_doctest.py.

01659 
01660 def test_debug(): r"""
01661 
01662 Create a docstring that we want to debug:
01663 
01664     >>> s = '''
01665     ...     >>> x = 12
01666     ...     >>> print(x)
01667     ...     12
01668     ...     '''
01669 
01670 Create some fake stdin input, to feed to the debugger:
01671 
01672     >>> real_stdin = sys.stdin
01673     >>> sys.stdin = _FakeInput(['next', 'print(x)', 'continue'])
01674 
01675 Run the debugger on the docstring, and then restore sys.stdin.
01676 
01677     >>> try: doctest.debug_src(s)
01678     ... finally: sys.stdin = real_stdin
01679     > <string>(1)<module>()
01680     (Pdb) next
01681     12
01682     --Return--
01683     > <string>(1)<module>()->None
01684     (Pdb) print(x)
01685     12
01686     (Pdb) continue
01687 
01688 """

We can test tests found in text files using a DocFileSuite.

   We create a suite by providing the names of one or more text
   files that include examples:

     >>> import unittest
     >>> suite = doctest.DocFileSuite('test_doctest.txt',
     ...                              'test_doctest2.txt',
     ...                              'test_doctest4.txt')
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=3 errors=0 failures=2>

   The test files are looked for in the directory containing the
   calling module.  A package keyword argument can be provided to
   specify a different relative location.

     >>> import unittest
     >>> suite = doctest.DocFileSuite('test_doctest.txt',
     ...                              'test_doctest2.txt',
     ...                              'test_doctest4.txt',
     ...                              package='test')
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=3 errors=0 failures=2>

   Support for using a package's __loader__.get_data() is also
   provided.

     >>> import unittest, pkgutil, test
     >>> added_loader = False
     >>> if not hasattr(test, '__loader__'):
     ...     test.__loader__ = pkgutil.get_loader(test)
     ...     added_loader = True
     >>> try:
     ...     suite = doctest.DocFileSuite('test_doctest.txt',
     ...                                  'test_doctest2.txt',
     ...                                  'test_doctest4.txt',
     ...                                  package='test')
     ...     suite.run(unittest.TestResult())
     ... finally:
     ...     if added_loader:
     ...         del test.__loader__
     <unittest.result.TestResult run=3 errors=0 failures=2>

   '/' should be used as a path separator.  It will be converted
   to a native separator at run time:

     >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=1 errors=0 failures=1>

   If DocFileSuite is used from an interactive session, then files
   are resolved relative to the directory of sys.argv[0]:

     >>> import types, os.path, test.test_doctest
     >>> save_argv = sys.argv
     >>> sys.argv = [test.test_doctest.__file__]
     >>> suite = doctest.DocFileSuite('test_doctest.txt',
     ...                              package=types.ModuleType('__main__'))
     >>> sys.argv = save_argv

   By setting `module_relative=False`, os-specific paths may be
   used (including absolute paths and paths relative to the
   working directory):

     >>> # Get the absolute path of the test package.
     >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
     >>> test_pkg_path = os.path.split(test_doctest_path)[0]

     >>> # Use it to find the absolute path of test_doctest.txt.
     >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')

     >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=1 errors=0 failures=1>

   It is an error to specify `package` when `module_relative=False`:

     >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
     ...                              package='test')
     Traceback (most recent call last):
     ValueError: Package may only be specified for module-relative paths.

   You can specify initial global variables:

     >>> suite = doctest.DocFileSuite('test_doctest.txt',
     ...                              'test_doctest2.txt',
     ...                              'test_doctest4.txt',
     ...                              globs={'favorite_color': 'blue'})
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=3 errors=0 failures=1>

   In this case, we supplied a missing favorite color. You can
   provide doctest options:

     >>> suite = doctest.DocFileSuite('test_doctest.txt',
     ...                              'test_doctest2.txt',
     ...                              'test_doctest4.txt',
     ...                         optionflags=doctest.DONT_ACCEPT_BLANKLINE,
     ...                              globs={'favorite_color': 'blue'})
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=3 errors=0 failures=2>

   And, you can provide setUp and tearDown functions:

     >>> def setUp(t):
     ...     import test.test_doctest
     ...     test.test_doctest.sillySetup = True

     >>> def tearDown(t):
     ...     import test.test_doctest
     ...     del test.test_doctest.sillySetup

   Here, we installed a silly variable that the test expects:

     >>> suite = doctest.DocFileSuite('test_doctest.txt',
     ...                              'test_doctest2.txt',
     ...                              'test_doctest4.txt',
     ...                              setUp=setUp, tearDown=tearDown)
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=3 errors=0 failures=1>

   But the tearDown restores sanity:

     >>> import test.test_doctest
     >>> test.test_doctest.sillySetup
     Traceback (most recent call last):
     ...
     AttributeError: 'module' object has no attribute 'sillySetup'

   The setUp and tearDown funtions are passed test objects.
   Here, we'll use a setUp function to set the favorite color in
   test_doctest.txt:

     >>> def setUp(test):
     ...     test.globs['favorite_color'] = 'blue'

     >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=1 errors=0 failures=0>

   Here, we didn't need to use a tearDown function because we
   modified the test globals.  The test globals are
   automatically cleared for us after a test.

   Tests in a file run using `DocFileSuite` can also access the
   `__file__` global, which is set to the name of the file
   containing the tests:

     >>> suite = doctest.DocFileSuite('test_doctest3.txt')
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=1 errors=0 failures=0>

   If the tests contain non-ASCII characters, we have to specify which
   encoding the file is encoded with. We do so by using the `encoding`
   parameter:

     >>> suite = doctest.DocFileSuite('test_doctest.txt',
     ...                              'test_doctest2.txt',
     ...                              'test_doctest4.txt',
     ...                              encoding='utf-8')
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=3 errors=0 failures=2>

Definition at line 1999 of file test_doctest.py.

01999 
02000 def test_DocFileSuite():
02001     """We can test tests found in text files using a DocFileSuite.
02002 
02003        We create a suite by providing the names of one or more text
02004        files that include examples:
02005 
02006          >>> import unittest
02007          >>> suite = doctest.DocFileSuite('test_doctest.txt',
02008          ...                              'test_doctest2.txt',
02009          ...                              'test_doctest4.txt')
02010          >>> suite.run(unittest.TestResult())
02011          <unittest.result.TestResult run=3 errors=0 failures=2>
02012 
02013        The test files are looked for in the directory containing the
02014        calling module.  A package keyword argument can be provided to
02015        specify a different relative location.
02016 
02017          >>> import unittest
02018          >>> suite = doctest.DocFileSuite('test_doctest.txt',
02019          ...                              'test_doctest2.txt',
02020          ...                              'test_doctest4.txt',
02021          ...                              package='test')
02022          >>> suite.run(unittest.TestResult())
02023          <unittest.result.TestResult run=3 errors=0 failures=2>
02024 
02025        Support for using a package's __loader__.get_data() is also
02026        provided.
02027 
02028          >>> import unittest, pkgutil, test
02029          >>> added_loader = False
02030          >>> if not hasattr(test, '__loader__'):
02031          ...     test.__loader__ = pkgutil.get_loader(test)
02032          ...     added_loader = True
02033          >>> try:
02034          ...     suite = doctest.DocFileSuite('test_doctest.txt',
02035          ...                                  'test_doctest2.txt',
02036          ...                                  'test_doctest4.txt',
02037          ...                                  package='test')
02038          ...     suite.run(unittest.TestResult())
02039          ... finally:
02040          ...     if added_loader:
02041          ...         del test.__loader__
02042          <unittest.result.TestResult run=3 errors=0 failures=2>
02043 
02044        '/' should be used as a path separator.  It will be converted
02045        to a native separator at run time:
02046 
02047          >>> suite = doctest.DocFileSuite('../test/test_doctest.txt')
02048          >>> suite.run(unittest.TestResult())
02049          <unittest.result.TestResult run=1 errors=0 failures=1>
02050 
02051        If DocFileSuite is used from an interactive session, then files
02052        are resolved relative to the directory of sys.argv[0]:
02053 
02054          >>> import types, os.path, test.test_doctest
02055          >>> save_argv = sys.argv
02056          >>> sys.argv = [test.test_doctest.__file__]
02057          >>> suite = doctest.DocFileSuite('test_doctest.txt',
02058          ...                              package=types.ModuleType('__main__'))
02059          >>> sys.argv = save_argv
02060 
02061        By setting `module_relative=False`, os-specific paths may be
02062        used (including absolute paths and paths relative to the
02063        working directory):
02064 
02065          >>> # Get the absolute path of the test package.
02066          >>> test_doctest_path = os.path.abspath(test.test_doctest.__file__)
02067          >>> test_pkg_path = os.path.split(test_doctest_path)[0]
02068 
02069          >>> # Use it to find the absolute path of test_doctest.txt.
02070          >>> test_file = os.path.join(test_pkg_path, 'test_doctest.txt')
02071 
02072          >>> suite = doctest.DocFileSuite(test_file, module_relative=False)
02073          >>> suite.run(unittest.TestResult())
02074          <unittest.result.TestResult run=1 errors=0 failures=1>
02075 
02076        It is an error to specify `package` when `module_relative=False`:
02077 
02078          >>> suite = doctest.DocFileSuite(test_file, module_relative=False,
02079          ...                              package='test')
02080          Traceback (most recent call last):
02081          ValueError: Package may only be specified for module-relative paths.
02082 
02083        You can specify initial global variables:
02084 
02085          >>> suite = doctest.DocFileSuite('test_doctest.txt',
02086          ...                              'test_doctest2.txt',
02087          ...                              'test_doctest4.txt',
02088          ...                              globs={'favorite_color': 'blue'})
02089          >>> suite.run(unittest.TestResult())
02090          <unittest.result.TestResult run=3 errors=0 failures=1>
02091 
02092        In this case, we supplied a missing favorite color. You can
02093        provide doctest options:
02094 
02095          >>> suite = doctest.DocFileSuite('test_doctest.txt',
02096          ...                              'test_doctest2.txt',
02097          ...                              'test_doctest4.txt',
02098          ...                         optionflags=doctest.DONT_ACCEPT_BLANKLINE,
02099          ...                              globs={'favorite_color': 'blue'})
02100          >>> suite.run(unittest.TestResult())
02101          <unittest.result.TestResult run=3 errors=0 failures=2>
02102 
02103        And, you can provide setUp and tearDown functions:
02104 
02105          >>> def setUp(t):
02106          ...     import test.test_doctest
02107          ...     test.test_doctest.sillySetup = True
02108 
02109          >>> def tearDown(t):
02110          ...     import test.test_doctest
02111          ...     del test.test_doctest.sillySetup
02112 
02113        Here, we installed a silly variable that the test expects:
02114 
02115          >>> suite = doctest.DocFileSuite('test_doctest.txt',
02116          ...                              'test_doctest2.txt',
02117          ...                              'test_doctest4.txt',
02118          ...                              setUp=setUp, tearDown=tearDown)
02119          >>> suite.run(unittest.TestResult())
02120          <unittest.result.TestResult run=3 errors=0 failures=1>
02121 
02122        But the tearDown restores sanity:
02123 
02124          >>> import test.test_doctest
02125          >>> test.test_doctest.sillySetup
02126          Traceback (most recent call last):
02127          ...
02128          AttributeError: 'module' object has no attribute 'sillySetup'
02129 
02130        The setUp and tearDown funtions are passed test objects.
02131        Here, we'll use a setUp function to set the favorite color in
02132        test_doctest.txt:
02133 
02134          >>> def setUp(test):
02135          ...     test.globs['favorite_color'] = 'blue'
02136 
02137          >>> suite = doctest.DocFileSuite('test_doctest.txt', setUp=setUp)
02138          >>> suite.run(unittest.TestResult())
02139          <unittest.result.TestResult run=1 errors=0 failures=0>
02140 
02141        Here, we didn't need to use a tearDown function because we
02142        modified the test globals.  The test globals are
02143        automatically cleared for us after a test.
02144 
02145        Tests in a file run using `DocFileSuite` can also access the
02146        `__file__` global, which is set to the name of the file
02147        containing the tests:
02148 
02149          >>> suite = doctest.DocFileSuite('test_doctest3.txt')
02150          >>> suite.run(unittest.TestResult())
02151          <unittest.result.TestResult run=1 errors=0 failures=0>
02152 
02153        If the tests contain non-ASCII characters, we have to specify which
02154        encoding the file is encoded with. We do so by using the `encoding`
02155        parameter:
02156 
02157          >>> suite = doctest.DocFileSuite('test_doctest.txt',
02158          ...                              'test_doctest2.txt',
02159          ...                              'test_doctest4.txt',
02160          ...                              encoding='utf-8')
02161          >>> suite.run(unittest.TestResult())
02162          <unittest.result.TestResult run=3 errors=0 failures=2>
02163 
02164        """

Definition at line 263 of file test_doctest.py.

00263 
00264 def test_DocTest(): r"""
00265 Unit tests for the `DocTest` class.
00266 
00267 DocTest is a collection of examples, extracted from a docstring, along
00268 with information about where the docstring comes from (a name,
00269 filename, and line number).  The docstring is parsed by the `DocTest`
00270 constructor:
00271 
00272     >>> docstring = '''
00273     ...     >>> print(12)
00274     ...     12
00275     ...
00276     ... Non-example text.
00277     ...
00278     ...     >>> print('another\example')
00279     ...     another
00280     ...     example
00281     ... '''
00282     >>> globs = {} # globals to run the test in.
00283     >>> parser = doctest.DocTestParser()
00284     >>> test = parser.get_doctest(docstring, globs, 'some_test',
00285     ...                           'some_file', 20)
00286     >>> print(test)
00287     <DocTest some_test from some_file:20 (2 examples)>
00288     >>> len(test.examples)
00289     2
00290     >>> e1, e2 = test.examples
00291     >>> (e1.source, e1.want, e1.lineno)
00292     ('print(12)\n', '12\n', 1)
00293     >>> (e2.source, e2.want, e2.lineno)
00294     ("print('another\\example')\n", 'another\nexample\n', 6)
00295 
00296 Source information (name, filename, and line number) is available as
00297 attributes on the doctest object:
00298 
00299     >>> (test.name, test.filename, test.lineno)
00300     ('some_test', 'some_file', 20)
00301 
00302 The line number of an example within its containing file is found by
00303 adding the line number of the example and the line number of its
00304 containing test:
00305 
00306     >>> test.lineno + e1.lineno
00307     21
00308     >>> test.lineno + e2.lineno
00309     26
00310 
00311 If the docstring contains inconsistant leading whitespace in the
00312 expected output of an example, then `DocTest` will raise a ValueError:
00313 
00314     >>> docstring = r'''
00315     ...       >>> print('bad\nindentation')
00316     ...       bad
00317     ...     indentation
00318     ...     '''
00319     >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
00320     Traceback (most recent call last):
00321     ValueError: line 4 of the docstring for some_test has inconsistent leading whitespace: 'indentation'
00322 
00323 If the docstring contains inconsistent leading whitespace on
00324 continuation lines, then `DocTest` will raise a ValueError:
00325 
00326     >>> docstring = r'''
00327     ...       >>> print(('bad indentation',
00328     ...     ...          2))
00329     ...       ('bad', 'indentation')
00330     ...     '''
00331     >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
00332     Traceback (most recent call last):
00333     ValueError: line 2 of the docstring for some_test has inconsistent leading whitespace: '...          2))'
00334 
00335 If there's no blank space after a PS1 prompt ('>>>'), then `DocTest`
00336 will raise a ValueError:
00337 
00338     >>> docstring = '>>>print(1)\n1'
00339     >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
00340     Traceback (most recent call last):
00341     ValueError: line 1 of the docstring for some_test lacks blank after >>>: '>>>print(1)'
00342 
00343 If there's no blank space after a PS2 prompt ('...'), then `DocTest`
00344 will raise a ValueError:
00345 
00346     >>> docstring = '>>> if 1:\n...print(1)\n1'
00347     >>> parser.get_doctest(docstring, globs, 'some_test', 'filename', 0)
00348     Traceback (most recent call last):
00349     ValueError: line 2 of the docstring for some_test lacks blank after ...: '...print(1)'
00350 
00351 """

Definition at line 352 of file test_doctest.py.

00352 
00353 def test_DocTestFinder(): r"""
00354 Unit tests for the `DocTestFinder` class.
00355 
00356 DocTestFinder is used to extract DocTests from an object's docstring
00357 and the docstrings of its contained objects.  It can be used with
00358 modules, functions, classes, methods, staticmethods, classmethods, and
00359 properties.
00360 
00361 Finding Tests in Functions
00362 ~~~~~~~~~~~~~~~~~~~~~~~~~~
00363 For a function whose docstring contains examples, DocTestFinder.find()
00364 will return a single test (for that function's docstring):
00365 
00366     >>> finder = doctest.DocTestFinder()
00367 
00368 We'll simulate a __file__ attr that ends in pyc:
00369 
00370     >>> import test.test_doctest
00371     >>> old = test.test_doctest.__file__
00372     >>> test.test_doctest.__file__ = 'test_doctest.pyc'
00373 
00374     >>> tests = finder.find(sample_func)
00375 
00376     >>> print(tests)  # doctest: +ELLIPSIS
00377     [<DocTest sample_func from ...:17 (1 example)>]
00378 
00379 The exact name depends on how test_doctest was invoked, so allow for
00380 leading path components.
00381 
00382     >>> tests[0].filename # doctest: +ELLIPSIS
00383     '...test_doctest.py'
00384 
00385     >>> test.test_doctest.__file__ = old
00386 
00387 
00388     >>> e = tests[0].examples[0]
00389     >>> (e.source, e.want, e.lineno)
00390     ('print(sample_func(22))\n', '44\n', 3)
00391 
00392 By default, tests are created for objects with no docstring:
00393 
00394     >>> def no_docstring(v):
00395     ...     pass
00396     >>> finder.find(no_docstring)
00397     []
00398 
00399 However, the optional argument `exclude_empty` to the DocTestFinder
00400 constructor can be used to exclude tests for objects with empty
00401 docstrings:
00402 
00403     >>> def no_docstring(v):
00404     ...     pass
00405     >>> excl_empty_finder = doctest.DocTestFinder(exclude_empty=True)
00406     >>> excl_empty_finder.find(no_docstring)
00407     []
00408 
00409 If the function has a docstring with no examples, then a test with no
00410 examples is returned.  (This lets `DocTestRunner` collect statistics
00411 about which functions have no tests -- but is that useful?  And should
00412 an empty test also be created when there's no docstring?)
00413 
00414     >>> def no_examples(v):
00415     ...     ''' no doctest examples '''
00416     >>> finder.find(no_examples) # doctest: +ELLIPSIS
00417     [<DocTest no_examples from ...:1 (no examples)>]
00418 
00419 Finding Tests in Classes
00420 ~~~~~~~~~~~~~~~~~~~~~~~~
00421 For a class, DocTestFinder will create a test for the class's
00422 docstring, and will recursively explore its contents, including
00423 methods, classmethods, staticmethods, properties, and nested classes.
00424 
00425     >>> finder = doctest.DocTestFinder()
00426     >>> tests = finder.find(SampleClass)
00427     >>> for t in tests:
00428     ...     print('%2s  %s' % (len(t.examples), t.name))
00429      3  SampleClass
00430      3  SampleClass.NestedClass
00431      1  SampleClass.NestedClass.__init__
00432      1  SampleClass.__init__
00433      2  SampleClass.a_classmethod
00434      1  SampleClass.a_property
00435      1  SampleClass.a_staticmethod
00436      1  SampleClass.double
00437      1  SampleClass.get
00438 
00439 New-style classes are also supported:
00440 
00441     >>> tests = finder.find(SampleNewStyleClass)
00442     >>> for t in tests:
00443     ...     print('%2s  %s' % (len(t.examples), t.name))
00444      1  SampleNewStyleClass
00445      1  SampleNewStyleClass.__init__
00446      1  SampleNewStyleClass.double
00447      1  SampleNewStyleClass.get
00448 
00449 Finding Tests in Modules
00450 ~~~~~~~~~~~~~~~~~~~~~~~~
00451 For a module, DocTestFinder will create a test for the class's
00452 docstring, and will recursively explore its contents, including
00453 functions, classes, and the `__test__` dictionary, if it exists:
00454 
00455     >>> # A module
00456     >>> import types
00457     >>> m = types.ModuleType('some_module')
00458     >>> def triple(val):
00459     ...     '''
00460     ...     >>> print(triple(11))
00461     ...     33
00462     ...     '''
00463     ...     return val*3
00464     >>> m.__dict__.update({
00465     ...     'sample_func': sample_func,
00466     ...     'SampleClass': SampleClass,
00467     ...     '__doc__': '''
00468     ...         Module docstring.
00469     ...             >>> print('module')
00470     ...             module
00471     ...         ''',
00472     ...     '__test__': {
00473     ...         'd': '>>> print(6)\n6\n>>> print(7)\n7\n',
00474     ...         'c': triple}})
00475 
00476     >>> finder = doctest.DocTestFinder()
00477     >>> # Use module=test.test_doctest, to prevent doctest from
00478     >>> # ignoring the objects since they weren't defined in m.
00479     >>> import test.test_doctest
00480     >>> tests = finder.find(m, module=test.test_doctest)
00481     >>> for t in tests:
00482     ...     print('%2s  %s' % (len(t.examples), t.name))
00483      1  some_module
00484      3  some_module.SampleClass
00485      3  some_module.SampleClass.NestedClass
00486      1  some_module.SampleClass.NestedClass.__init__
00487      1  some_module.SampleClass.__init__
00488      2  some_module.SampleClass.a_classmethod
00489      1  some_module.SampleClass.a_property
00490      1  some_module.SampleClass.a_staticmethod
00491      1  some_module.SampleClass.double
00492      1  some_module.SampleClass.get
00493      1  some_module.__test__.c
00494      2  some_module.__test__.d
00495      1  some_module.sample_func
00496 
00497 Duplicate Removal
00498 ~~~~~~~~~~~~~~~~~
00499 If a single object is listed twice (under different names), then tests
00500 will only be generated for it once:
00501 
00502     >>> from test import doctest_aliases
00503     >>> assert doctest_aliases.TwoNames.f
00504     >>> assert doctest_aliases.TwoNames.g
00505     >>> tests = excl_empty_finder.find(doctest_aliases)
00506     >>> print(len(tests))
00507     2
00508     >>> print(tests[0].name)
00509     test.doctest_aliases.TwoNames
00510 
00511     TwoNames.f and TwoNames.g are bound to the same object.
00512     We can't guess which will be found in doctest's traversal of
00513     TwoNames.__dict__ first, so we have to allow for either.
00514 
00515     >>> tests[1].name.split('.')[-1] in ['f', 'g']
00516     True
00517 
00518 Empty Tests
00519 ~~~~~~~~~~~
00520 By default, an object with no doctests doesn't create any tests:
00521 
00522     >>> tests = doctest.DocTestFinder().find(SampleClass)
00523     >>> for t in tests:
00524     ...     print('%2s  %s' % (len(t.examples), t.name))
00525      3  SampleClass
00526      3  SampleClass.NestedClass
00527      1  SampleClass.NestedClass.__init__
00528      1  SampleClass.__init__
00529      2  SampleClass.a_classmethod
00530      1  SampleClass.a_property
00531      1  SampleClass.a_staticmethod
00532      1  SampleClass.double
00533      1  SampleClass.get
00534 
00535 By default, that excluded objects with no doctests.  exclude_empty=False
00536 tells it to include (empty) tests for objects with no doctests.  This feature
00537 is really to support backward compatibility in what doctest.master.summarize()
00538 displays.
00539 
00540     >>> tests = doctest.DocTestFinder(exclude_empty=False).find(SampleClass)
00541     >>> for t in tests:
00542     ...     print('%2s  %s' % (len(t.examples), t.name))
00543      3  SampleClass
00544      3  SampleClass.NestedClass
00545      1  SampleClass.NestedClass.__init__
00546      0  SampleClass.NestedClass.get
00547      0  SampleClass.NestedClass.square
00548      1  SampleClass.__init__
00549      2  SampleClass.a_classmethod
00550      1  SampleClass.a_property
00551      1  SampleClass.a_staticmethod
00552      1  SampleClass.double
00553      1  SampleClass.get
00554 
00555 Turning off Recursion
00556 ~~~~~~~~~~~~~~~~~~~~~
00557 DocTestFinder can be told not to look for tests in contained objects
00558 using the `recurse` flag:
00559 
00560     >>> tests = doctest.DocTestFinder(recurse=False).find(SampleClass)
00561     >>> for t in tests:
00562     ...     print('%2s  %s' % (len(t.examples), t.name))
00563      3  SampleClass
00564 
00565 Line numbers
00566 ~~~~~~~~~~~~
00567 DocTestFinder finds the line number of each example:
00568 
00569     >>> def f(x):
00570     ...     '''
00571     ...     >>> x = 12
00572     ...
00573     ...     some text
00574     ...
00575     ...     >>> # examples are not created for comments & bare prompts.
00576     ...     >>>
00577     ...     ...
00578     ...
00579     ...     >>> for x in range(10):
00580     ...     ...     print(x, end=' ')
00581     ...     0 1 2 3 4 5 6 7 8 9
00582     ...     >>> x//2
00583     ...     6
00584     ...     '''
00585     >>> test = doctest.DocTestFinder().find(f)[0]
00586     >>> [e.lineno for e in test.examples]
00587     [1, 9, 12]
00588 """

Definition at line 589 of file test_doctest.py.

00589 
00590 def test_DocTestParser(): r"""
00591 Unit tests for the `DocTestParser` class.
00592 
00593 DocTestParser is used to parse docstrings containing doctest examples.
00594 
00595 The `parse` method divides a docstring into examples and intervening
00596 text:
00597 
00598     >>> s = '''
00599     ...     >>> x, y = 2, 3  # no output expected
00600     ...     >>> if 1:
00601     ...     ...     print(x)
00602     ...     ...     print(y)
00603     ...     2
00604     ...     3
00605     ...
00606     ...     Some text.
00607     ...     >>> x+y
00608     ...     5
00609     ...     '''
00610     >>> parser = doctest.DocTestParser()
00611     >>> for piece in parser.parse(s):
00612     ...     if isinstance(piece, doctest.Example):
00613     ...         print('Example:', (piece.source, piece.want, piece.lineno))
00614     ...     else:
00615     ...         print('   Text:', repr(piece))
00616        Text: '\n'
00617     Example: ('x, y = 2, 3  # no output expected\n', '', 1)
00618        Text: ''
00619     Example: ('if 1:\n    print(x)\n    print(y)\n', '2\n3\n', 2)
00620        Text: '\nSome text.\n'
00621     Example: ('x+y\n', '5\n', 9)
00622        Text: ''
00623 
00624 The `get_examples` method returns just the examples:
00625 
00626     >>> for piece in parser.get_examples(s):
00627     ...     print((piece.source, piece.want, piece.lineno))
00628     ('x, y = 2, 3  # no output expected\n', '', 1)
00629     ('if 1:\n    print(x)\n    print(y)\n', '2\n3\n', 2)
00630     ('x+y\n', '5\n', 9)
00631 
00632 The `get_doctest` method creates a Test from the examples, along with the
00633 given arguments:
00634 
00635     >>> test = parser.get_doctest(s, {}, 'name', 'filename', lineno=5)
00636     >>> (test.name, test.filename, test.lineno)
00637     ('name', 'filename', 5)
00638     >>> for piece in test.examples:
00639     ...     print((piece.source, piece.want, piece.lineno))
00640     ('x, y = 2, 3  # no output expected\n', '', 1)
00641     ('if 1:\n    print(x)\n    print(y)\n', '2\n3\n', 2)
00642     ('x+y\n', '5\n', 9)
00643 """

DocTestSuite creates a unittest test suite from a doctest.

   We create a Suite by providing a module.  A module can be provided
   by passing a module object:

     >>> import unittest
     >>> import test.sample_doctest
     >>> suite = doctest.DocTestSuite(test.sample_doctest)
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=9 errors=0 failures=4>

   We can also supply the module by name:

     >>> suite = doctest.DocTestSuite('test.sample_doctest')
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=9 errors=0 failures=4>

   We can use the current module:

     >>> suite = test.sample_doctest.test_suite()
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=9 errors=0 failures=4>

   We can supply global variables.  If we pass globs, they will be
   used instead of the module globals.  Here we'll pass an empty
   globals, triggering an extra error:

     >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=9 errors=0 failures=5>

   Alternatively, we can provide extra globals.  Here we'll make an
   error go away by providing an extra global variable:

     >>> suite = doctest.DocTestSuite('test.sample_doctest',
     ...                              extraglobs={'y': 1})
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=9 errors=0 failures=3>

   You can pass option flags.  Here we'll cause an extra error
   by disabling the blank-line feature:

     >>> suite = doctest.DocTestSuite('test.sample_doctest',
     ...                      optionflags=doctest.DONT_ACCEPT_BLANKLINE)
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=9 errors=0 failures=5>

   You can supply setUp and tearDown functions:

     >>> def setUp(t):
     ...     import test.test_doctest
     ...     test.test_doctest.sillySetup = True

     >>> def tearDown(t):
     ...     import test.test_doctest
     ...     del test.test_doctest.sillySetup

   Here, we installed a silly variable that the test expects:

     >>> suite = doctest.DocTestSuite('test.sample_doctest',
     ...      setUp=setUp, tearDown=tearDown)
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=9 errors=0 failures=3>

   But the tearDown restores sanity:

     >>> import test.test_doctest
     >>> test.test_doctest.sillySetup
     Traceback (most recent call last):
     ...
     AttributeError: 'module' object has no attribute 'sillySetup'

   The setUp and tearDown funtions are passed test objects. Here
   we'll use the setUp function to supply the missing variable y:

     >>> def setUp(test):
     ...     test.globs['y'] = 1

     >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
     >>> suite.run(unittest.TestResult())
     <unittest.result.TestResult run=9 errors=0 failures=3>

   Here, we didn't need to use a tearDown function because we
   modified the test globals, which are a copy of the
   sample_doctest module dictionary.  The test globals are
   automatically cleared for us after a test.

Definition at line 1910 of file test_doctest.py.

01910 
01911 def test_DocTestSuite():
01912     """DocTestSuite creates a unittest test suite from a doctest.
01913 
01914        We create a Suite by providing a module.  A module can be provided
01915        by passing a module object:
01916 
01917          >>> import unittest
01918          >>> import test.sample_doctest
01919          >>> suite = doctest.DocTestSuite(test.sample_doctest)
01920          >>> suite.run(unittest.TestResult())
01921          <unittest.result.TestResult run=9 errors=0 failures=4>
01922 
01923        We can also supply the module by name:
01924 
01925          >>> suite = doctest.DocTestSuite('test.sample_doctest')
01926          >>> suite.run(unittest.TestResult())
01927          <unittest.result.TestResult run=9 errors=0 failures=4>
01928 
01929        We can use the current module:
01930 
01931          >>> suite = test.sample_doctest.test_suite()
01932          >>> suite.run(unittest.TestResult())
01933          <unittest.result.TestResult run=9 errors=0 failures=4>
01934 
01935        We can supply global variables.  If we pass globs, they will be
01936        used instead of the module globals.  Here we'll pass an empty
01937        globals, triggering an extra error:
01938 
01939          >>> suite = doctest.DocTestSuite('test.sample_doctest', globs={})
01940          >>> suite.run(unittest.TestResult())
01941          <unittest.result.TestResult run=9 errors=0 failures=5>
01942 
01943        Alternatively, we can provide extra globals.  Here we'll make an
01944        error go away by providing an extra global variable:
01945 
01946          >>> suite = doctest.DocTestSuite('test.sample_doctest',
01947          ...                              extraglobs={'y': 1})
01948          >>> suite.run(unittest.TestResult())
01949          <unittest.result.TestResult run=9 errors=0 failures=3>
01950 
01951        You can pass option flags.  Here we'll cause an extra error
01952        by disabling the blank-line feature:
01953 
01954          >>> suite = doctest.DocTestSuite('test.sample_doctest',
01955          ...                      optionflags=doctest.DONT_ACCEPT_BLANKLINE)
01956          >>> suite.run(unittest.TestResult())
01957          <unittest.result.TestResult run=9 errors=0 failures=5>
01958 
01959        You can supply setUp and tearDown functions:
01960 
01961          >>> def setUp(t):
01962          ...     import test.test_doctest
01963          ...     test.test_doctest.sillySetup = True
01964 
01965          >>> def tearDown(t):
01966          ...     import test.test_doctest
01967          ...     del test.test_doctest.sillySetup
01968 
01969        Here, we installed a silly variable that the test expects:
01970 
01971          >>> suite = doctest.DocTestSuite('test.sample_doctest',
01972          ...      setUp=setUp, tearDown=tearDown)
01973          >>> suite.run(unittest.TestResult())
01974          <unittest.result.TestResult run=9 errors=0 failures=3>
01975 
01976        But the tearDown restores sanity:
01977 
01978          >>> import test.test_doctest
01979          >>> test.test_doctest.sillySetup
01980          Traceback (most recent call last):
01981          ...
01982          AttributeError: 'module' object has no attribute 'sillySetup'
01983 
01984        The setUp and tearDown funtions are passed test objects. Here
01985        we'll use the setUp function to supply the missing variable y:
01986 
01987          >>> def setUp(test):
01988          ...     test.globs['y'] = 1
01989 
01990          >>> suite = doctest.DocTestSuite('test.sample_doctest', setUp=setUp)
01991          >>> suite.run(unittest.TestResult())
01992          <unittest.result.TestResult run=9 errors=0 failures=3>
01993 
01994        Here, we didn't need to use a tearDown function because we
01995        modified the test globals, which are a copy of the
01996        sample_doctest module dictionary.  The test globals are
01997        automatically cleared for us after a test.
01998        """

Test Cases.

Definition at line 157 of file test_doctest.py.

00157 
00158 def test_Example(): r"""
00159 Unit tests for the `Example` class.
00160 
00161 Example is a simple container class that holds:
00162   - `source`: A source string.
00163   - `want`: An expected output string.
00164   - `exc_msg`: An expected exception message string (or None if no
00165     exception is expected).
00166   - `lineno`: A line number (within the docstring).
00167   - `indent`: The example's indentation in the input string.
00168   - `options`: An option dictionary, mapping option flags to True or
00169     False.
00170 
00171 These attributes are set by the constructor.  `source` and `want` are
00172 required; the other attributes all have default values:
00173 
00174     >>> example = doctest.Example('print(1)', '1\n')
00175     >>> (example.source, example.want, example.exc_msg,
00176     ...  example.lineno, example.indent, example.options)
00177     ('print(1)\n', '1\n', None, 0, 0, {})
00178 
00179 The first three attributes (`source`, `want`, and `exc_msg`) may be
00180 specified positionally; the remaining arguments should be specified as
00181 keyword arguments:
00182 
00183     >>> exc_msg = 'IndexError: pop from an empty list'
00184     >>> example = doctest.Example('[].pop()', '', exc_msg,
00185     ...                           lineno=5, indent=4,
00186     ...                           options={doctest.ELLIPSIS: True})
00187     >>> (example.source, example.want, example.exc_msg,
00188     ...  example.lineno, example.indent, example.options)
00189     ('[].pop()\n', '', 'IndexError: pop from an empty list\n', 5, 4, {8: True})
00190 
00191 The constructor normalizes the `source` string to end in a newline:
00192 
00193     Source spans a single line: no terminating newline.
00194     >>> e = doctest.Example('print(1)', '1\n')
00195     >>> e.source, e.want
00196     ('print(1)\n', '1\n')
00197 
00198     >>> e = doctest.Example('print(1)\n', '1\n')
00199     >>> e.source, e.want
00200     ('print(1)\n', '1\n')
00201 
00202     Source spans multiple lines: require terminating newline.
00203     >>> e = doctest.Example('print(1);\nprint(2)\n', '1\n2\n')
00204     >>> e.source, e.want
00205     ('print(1);\nprint(2)\n', '1\n2\n')
00206 
00207     >>> e = doctest.Example('print(1);\nprint(2)', '1\n2\n')
00208     >>> e.source, e.want
00209     ('print(1);\nprint(2)\n', '1\n2\n')
00210 
00211     Empty source string (which should never appear in real examples)
00212     >>> e = doctest.Example('', '')
00213     >>> e.source, e.want
00214     ('\n', '')
00215 
00216 The constructor normalizes the `want` string to end in a newline,
00217 unless it's the empty string:
00218 
00219     >>> e = doctest.Example('print(1)', '1\n')
00220     >>> e.source, e.want
00221     ('print(1)\n', '1\n')
00222 
00223     >>> e = doctest.Example('print(1)', '1')
00224     >>> e.source, e.want
00225     ('print(1)\n', '1\n')
00226 
00227     >>> e = doctest.Example('print', '')
00228     >>> e.source, e.want
00229     ('print\n', '')
00230 
00231 The constructor normalizes the `exc_msg` string to end in a newline,
00232 unless it's `None`:
00233 
00234     Message spans one line
00235     >>> exc_msg = 'IndexError: pop from an empty list'
00236     >>> e = doctest.Example('[].pop()', '', exc_msg)
00237     >>> e.exc_msg
00238     'IndexError: pop from an empty list\n'
00239 
00240     >>> exc_msg = 'IndexError: pop from an empty list\n'
00241     >>> e = doctest.Example('[].pop()', '', exc_msg)
00242     >>> e.exc_msg
00243     'IndexError: pop from an empty list\n'
00244 
00245     Message spans multiple lines
00246     >>> exc_msg = 'ValueError: 1\n  2'
00247     >>> e = doctest.Example('raise ValueError("1\n  2")', '', exc_msg)
00248     >>> e.exc_msg
00249     'ValueError: 1\n  2\n'
00250 
00251     >>> exc_msg = 'ValueError: 1\n  2\n'
00252     >>> e = doctest.Example('raise ValueError("1\n  2")', '', exc_msg)
00253     >>> e.exc_msg
00254     'ValueError: 1\n  2\n'
00255 
00256     Empty (but non-None) exception message (which should never appear
00257     in real examples)
00258     >>> exc_msg = ''
00259     >>> e = doctest.Example('raise X()', '', exc_msg)
00260     >>> e.exc_msg
00261     '\n'
00262 """

Main.

Definition at line 2474 of file test_doctest.py.

02474 
02475 def test_main():
02476     # Check the doctest cases in doctest itself:
02477     support.run_doctest(doctest, verbosity=True)
02478     # Check the doctest cases defined here:
02479     from test import test_doctest
02480     support.run_doctest(test_doctest, verbosity=True)

Here is the caller graph for this function:

Using pdb.set_trace from a doctest.

You can use pdb.set_trace from a doctest.  To do so, you must
retrieve the set_trace function from the pdb module at the time
you use it.  The doctest module changes sys.stdout so that it can
capture program output.  It also temporarily replaces pdb.set_trace
with a version that restores stdout.  This is necessary for you to
see debugger output.

  >>> doc = '''
  ... >>> x = 42
  ... >>> raise Exception('clé')
  ... Traceback (most recent call last):
  ... Exception: clé
  ... >>> import pdb; pdb.set_trace()
  ... '''
  >>> parser = doctest.DocTestParser()
  >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
  >>> runner = doctest.DocTestRunner(verbose=False)

To demonstrate this, we'll create a fake standard input that
captures our debugger input:

  >>> import tempfile
  >>> real_stdin = sys.stdin
  >>> sys.stdin = _FakeInput([
  ...    'print(x)',  # print data defined by the example
  ...    'continue', # stop debugging
  ...    ''])

  >>> try: runner.run(test)
  ... finally: sys.stdin = real_stdin
  --Return--
  > <doctest foo-bar@baz[2]>(1)<module>()->None
  -> import pdb; pdb.set_trace()
  (Pdb) print(x)
  42
  (Pdb) continue
  TestResults(failed=0, attempted=3)

  You can also put pdb.set_trace in a function called from a test:

  >>> def calls_set_trace():
  ...    y=2
  ...    import pdb; pdb.set_trace()

  >>> doc = '''
  ... >>> x=1
  ... >>> calls_set_trace()
  ... '''
  >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
  >>> real_stdin = sys.stdin
  >>> sys.stdin = _FakeInput([
  ...    'print(y)',  # print data defined in the function
  ...    'up',       # out of function
  ...    'print(x)',  # print data defined by the example
  ...    'continue', # stop debugging
  ...    ''])

  >>> try:
  ...     runner.run(test)
  ... finally:
  ...     sys.stdin = real_stdin
  --Return--
  > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
  -> import pdb; pdb.set_trace()
  (Pdb) print(y)
  2
  (Pdb) up
  > <doctest foo-bar@baz[1]>(1)<module>()
  -> calls_set_trace()
  (Pdb) print(x)
  1
  (Pdb) continue
  TestResults(failed=0, attempted=2)

During interactive debugging, source code is shown, even for
doctest examples:

  >>> doc = '''
  ... >>> def f(x):
  ... ...     g(x*2)
  ... >>> def g(x):
  ... ...     print(x+3)
  ... ...     import pdb; pdb.set_trace()
  ... >>> f(3)
  ... '''
  >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
  >>> real_stdin = sys.stdin
  >>> sys.stdin = _FakeInput([
  ...    'list',     # list source from example 2
  ...    'next',     # return from g()
  ...    'list',     # list source from example 1
  ...    'next',     # return from f()
  ...    'list',     # list source from example 3
  ...    'continue', # stop debugging
  ...    ''])
  >>> try: runner.run(test)
  ... finally: sys.stdin = real_stdin
  ... # doctest: +NORMALIZE_WHITESPACE
  --Return--
  > <doctest foo-bar@baz[1]>(3)g()->None
  -> import pdb; pdb.set_trace()
  (Pdb) list
    1     def g(x):
    2         print(x+3)
    3  ->     import pdb; pdb.set_trace()
  [EOF]
  (Pdb) next
  --Return--
  > <doctest foo-bar@baz[0]>(2)f()->None
  -> g(x*2)
  (Pdb) list
    1     def f(x):
    2  ->     g(x*2)
  [EOF]
  (Pdb) next
  --Return--
  > <doctest foo-bar@baz[2]>(1)<module>()->None
  -> f(3)
  (Pdb) list
    1  -> f(3)
  [EOF]
  (Pdb) continue
  **********************************************************************
  File "foo-bar@baz.py", line 7, in foo-bar@baz
  Failed example:
      f(3)
  Expected nothing
  Got:
      9
  TestResults(failed=1, attempted=3)

Definition at line 1689 of file test_doctest.py.

01689 
01690 def test_pdb_set_trace():
01691     """Using pdb.set_trace from a doctest.
01692 
01693     You can use pdb.set_trace from a doctest.  To do so, you must
01694     retrieve the set_trace function from the pdb module at the time
01695     you use it.  The doctest module changes sys.stdout so that it can
01696     capture program output.  It also temporarily replaces pdb.set_trace
01697     with a version that restores stdout.  This is necessary for you to
01698     see debugger output.
01699 
01700       >>> doc = '''
01701       ... >>> x = 42
01702       ... >>> raise Exception('clé')
01703       ... Traceback (most recent call last):
01704       ... Exception: clé
01705       ... >>> import pdb; pdb.set_trace()
01706       ... '''
01707       >>> parser = doctest.DocTestParser()
01708       >>> test = parser.get_doctest(doc, {}, "foo-bar@baz", "foo-bar@baz.py", 0)
01709       >>> runner = doctest.DocTestRunner(verbose=False)
01710 
01711     To demonstrate this, we'll create a fake standard input that
01712     captures our debugger input:
01713 
01714       >>> import tempfile
01715       >>> real_stdin = sys.stdin
01716       >>> sys.stdin = _FakeInput([
01717       ...    'print(x)',  # print data defined by the example
01718       ...    'continue', # stop debugging
01719       ...    ''])
01720 
01721       >>> try: runner.run(test)
01722       ... finally: sys.stdin = real_stdin
01723       --Return--
01724       > <doctest foo-bar@baz[2]>(1)<module>()->None
01725       -> import pdb; pdb.set_trace()
01726       (Pdb) print(x)
01727       42
01728       (Pdb) continue
01729       TestResults(failed=0, attempted=3)
01730 
01731       You can also put pdb.set_trace in a function called from a test:
01732 
01733       >>> def calls_set_trace():
01734       ...    y=2
01735       ...    import pdb; pdb.set_trace()
01736 
01737       >>> doc = '''
01738       ... >>> x=1
01739       ... >>> calls_set_trace()
01740       ... '''
01741       >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
01742       >>> real_stdin = sys.stdin
01743       >>> sys.stdin = _FakeInput([
01744       ...    'print(y)',  # print data defined in the function
01745       ...    'up',       # out of function
01746       ...    'print(x)',  # print data defined by the example
01747       ...    'continue', # stop debugging
01748       ...    ''])
01749 
01750       >>> try:
01751       ...     runner.run(test)
01752       ... finally:
01753       ...     sys.stdin = real_stdin
01754       --Return--
01755       > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
01756       -> import pdb; pdb.set_trace()
01757       (Pdb) print(y)
01758       2
01759       (Pdb) up
01760       > <doctest foo-bar@baz[1]>(1)<module>()
01761       -> calls_set_trace()
01762       (Pdb) print(x)
01763       1
01764       (Pdb) continue
01765       TestResults(failed=0, attempted=2)
01766 
01767     During interactive debugging, source code is shown, even for
01768     doctest examples:
01769 
01770       >>> doc = '''
01771       ... >>> def f(x):
01772       ... ...     g(x*2)
01773       ... >>> def g(x):
01774       ... ...     print(x+3)
01775       ... ...     import pdb; pdb.set_trace()
01776       ... >>> f(3)
01777       ... '''
01778       >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
01779       >>> real_stdin = sys.stdin
01780       >>> sys.stdin = _FakeInput([
01781       ...    'list',     # list source from example 2
01782       ...    'next',     # return from g()
01783       ...    'list',     # list source from example 1
01784       ...    'next',     # return from f()
01785       ...    'list',     # list source from example 3
01786       ...    'continue', # stop debugging
01787       ...    ''])
01788       >>> try: runner.run(test)
01789       ... finally: sys.stdin = real_stdin
01790       ... # doctest: +NORMALIZE_WHITESPACE
01791       --Return--
01792       > <doctest foo-bar@baz[1]>(3)g()->None
01793       -> import pdb; pdb.set_trace()
01794       (Pdb) list
01795         1     def g(x):
01796         2         print(x+3)
01797         3  ->     import pdb; pdb.set_trace()
01798       [EOF]
01799       (Pdb) next
01800       --Return--
01801       > <doctest foo-bar@baz[0]>(2)f()->None
01802       -> g(x*2)
01803       (Pdb) list
01804         1     def f(x):
01805         2  ->     g(x*2)
01806       [EOF]
01807       (Pdb) next
01808       --Return--
01809       > <doctest foo-bar@baz[2]>(1)<module>()->None
01810       -> f(3)
01811       (Pdb) list
01812         1  -> f(3)
01813       [EOF]
01814       (Pdb) continue
01815       **********************************************************************
01816       File "foo-bar@baz.py", line 7, in foo-bar@baz
01817       Failed example:
01818           f(3)
01819       Expected nothing
01820       Got:
01821           9
01822       TestResults(failed=1, attempted=3)
01823       """

This illustrates more-demanding use of set_trace with nested functions.

>>> class C(object):
...     def calls_set_trace(self):
...         y = 1
...         import pdb; pdb.set_trace()
...         self.f1()
...         y = 2
...     def f1(self):
...         x = 1
...         self.f2()
...         x = 2
...     def f2(self):
...         z = 1
...         z = 2

>>> calls_set_trace = C().calls_set_trace

>>> doc = '''
... >>> a = 1
... >>> calls_set_trace()
... '''
>>> parser = doctest.DocTestParser()
>>> runner = doctest.DocTestRunner(verbose=False)
>>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
>>> real_stdin = sys.stdin
>>> sys.stdin = _FakeInput([
...    'print(y)',  # print data defined in the function
...    'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
...    'up', 'print(x)',
...    'up', 'print(y)',
...    'up', 'print(foo)',
...    'continue', # stop debugging
...    ''])

>>> try:
...     runner.run(test)
... finally:
...     sys.stdin = real_stdin
... # doctest: +REPORT_NDIFF
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
-> self.f1()
(Pdb) print(y)
1
(Pdb) step
--Call--
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
-> def f1(self):
(Pdb) step
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
-> x = 1
(Pdb) step
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
-> self.f2()
(Pdb) step
--Call--
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
-> def f2(self):
(Pdb) step
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
-> z = 1
(Pdb) step
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
-> z = 2
(Pdb) print(z)
1
(Pdb) up
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
-> self.f2()
(Pdb) print(x)
1
(Pdb) up
> <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
-> self.f1()
(Pdb) print(y)
1
(Pdb) up
> <doctest foo-bar@baz[1]>(1)<module>()
-> calls_set_trace()
(Pdb) print(foo)
*** NameError: name 'foo' is not defined
(Pdb) continue
TestResults(failed=0, attempted=2)

Definition at line 1824 of file test_doctest.py.

01824 
01825 def test_pdb_set_trace_nested():
01826     """This illustrates more-demanding use of set_trace with nested functions.
01827 
01828     >>> class C(object):
01829     ...     def calls_set_trace(self):
01830     ...         y = 1
01831     ...         import pdb; pdb.set_trace()
01832     ...         self.f1()
01833     ...         y = 2
01834     ...     def f1(self):
01835     ...         x = 1
01836     ...         self.f2()
01837     ...         x = 2
01838     ...     def f2(self):
01839     ...         z = 1
01840     ...         z = 2
01841 
01842     >>> calls_set_trace = C().calls_set_trace
01843 
01844     >>> doc = '''
01845     ... >>> a = 1
01846     ... >>> calls_set_trace()
01847     ... '''
01848     >>> parser = doctest.DocTestParser()
01849     >>> runner = doctest.DocTestRunner(verbose=False)
01850     >>> test = parser.get_doctest(doc, globals(), "foo-bar@baz", "foo-bar@baz.py", 0)
01851     >>> real_stdin = sys.stdin
01852     >>> sys.stdin = _FakeInput([
01853     ...    'print(y)',  # print data defined in the function
01854     ...    'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
01855     ...    'up', 'print(x)',
01856     ...    'up', 'print(y)',
01857     ...    'up', 'print(foo)',
01858     ...    'continue', # stop debugging
01859     ...    ''])
01860 
01861     >>> try:
01862     ...     runner.run(test)
01863     ... finally:
01864     ...     sys.stdin = real_stdin
01865     ... # doctest: +REPORT_NDIFF
01866     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
01867     -> self.f1()
01868     (Pdb) print(y)
01869     1
01870     (Pdb) step
01871     --Call--
01872     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
01873     -> def f1(self):
01874     (Pdb) step
01875     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
01876     -> x = 1
01877     (Pdb) step
01878     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
01879     -> self.f2()
01880     (Pdb) step
01881     --Call--
01882     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
01883     -> def f2(self):
01884     (Pdb) step
01885     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
01886     -> z = 1
01887     (Pdb) step
01888     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
01889     -> z = 2
01890     (Pdb) print(z)
01891     1
01892     (Pdb) up
01893     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
01894     -> self.f2()
01895     (Pdb) print(x)
01896     1
01897     (Pdb) up
01898     > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
01899     -> self.f1()
01900     (Pdb) print(y)
01901     1
01902     (Pdb) up
01903     > <doctest foo-bar@baz[1]>(1)<module>()
01904     -> calls_set_trace()
01905     (Pdb) print(foo)
01906     *** NameError: name 'foo' is not defined
01907     (Pdb) continue
01908     TestResults(failed=0, attempted=2)
01909 """

Definition at line 2250 of file test_doctest.py.

02250 
02251 def test_testfile(): r"""
02252 Tests for the `testfile()` function.  This function runs all the
02253 doctest examples in a given file.  In its simple invokation, it is
02254 called with the name of a file, which is taken to be relative to the
02255 calling module.  The return value is (#failures, #tests).
02256 
02257 We don't want `-v` in sys.argv for these tests.
02258 
02259     >>> save_argv = sys.argv
02260     >>> if '-v' in sys.argv:
02261     ...     sys.argv = [arg for arg in save_argv if arg != '-v']
02262 
02263 
02264     >>> doctest.testfile('test_doctest.txt') # doctest: +ELLIPSIS
02265     **********************************************************************
02266     File "...", line 6, in test_doctest.txt
02267     Failed example:
02268         favorite_color
02269     Exception raised:
02270         ...
02271         NameError: name 'favorite_color' is not defined
02272     **********************************************************************
02273     1 items had failures:
02274        1 of   2 in test_doctest.txt
02275     ***Test Failed*** 1 failures.
02276     TestResults(failed=1, attempted=2)
02277     >>> doctest.master = None  # Reset master.
02278 
02279 (Note: we'll be clearing doctest.master after each call to
02280 `doctest.testfile`, to suppress warnings about multiple tests with the
02281 same name.)
02282 
02283 Globals may be specified with the `globs` and `extraglobs` parameters:
02284 
02285     >>> globs = {'favorite_color': 'blue'}
02286     >>> doctest.testfile('test_doctest.txt', globs=globs)
02287     TestResults(failed=0, attempted=2)
02288     >>> doctest.master = None  # Reset master.
02289 
02290     >>> extraglobs = {'favorite_color': 'red'}
02291     >>> doctest.testfile('test_doctest.txt', globs=globs,
02292     ...                  extraglobs=extraglobs) # doctest: +ELLIPSIS
02293     **********************************************************************
02294     File "...", line 6, in test_doctest.txt
02295     Failed example:
02296         favorite_color
02297     Expected:
02298         'blue'
02299     Got:
02300         'red'
02301     **********************************************************************
02302     1 items had failures:
02303        1 of   2 in test_doctest.txt
02304     ***Test Failed*** 1 failures.
02305     TestResults(failed=1, attempted=2)
02306     >>> doctest.master = None  # Reset master.
02307 
02308 The file may be made relative to a given module or package, using the
02309 optional `module_relative` parameter:
02310 
02311     >>> doctest.testfile('test_doctest.txt', globs=globs,
02312     ...                  module_relative='test')
02313     TestResults(failed=0, attempted=2)
02314     >>> doctest.master = None  # Reset master.
02315 
02316 Verbosity can be increased with the optional `verbose` parameter:
02317 
02318     >>> doctest.testfile('test_doctest.txt', globs=globs, verbose=True)
02319     Trying:
02320         favorite_color
02321     Expecting:
02322         'blue'
02323     ok
02324     Trying:
02325         if 1:
02326            print('a')
02327            print()
02328            print('b')
02329     Expecting:
02330         a
02331         <BLANKLINE>
02332         b
02333     ok
02334     1 items passed all tests:
02335        2 tests in test_doctest.txt
02336     2 tests in 1 items.
02337     2 passed and 0 failed.
02338     Test passed.
02339     TestResults(failed=0, attempted=2)
02340     >>> doctest.master = None  # Reset master.
02341 
02342 The name of the test may be specified with the optional `name`
02343 parameter:
02344 
02345     >>> doctest.testfile('test_doctest.txt', name='newname')
02346     ... # doctest: +ELLIPSIS
02347     **********************************************************************
02348     File "...", line 6, in newname
02349     ...
02350     TestResults(failed=1, attempted=2)
02351     >>> doctest.master = None  # Reset master.
02352 
02353 The summary report may be suppressed with the optional `report`
02354 parameter:
02355 
02356     >>> doctest.testfile('test_doctest.txt', report=False)
02357     ... # doctest: +ELLIPSIS
02358     **********************************************************************
02359     File "...", line 6, in test_doctest.txt
02360     Failed example:
02361         favorite_color
02362     Exception raised:
02363         ...
02364         NameError: name 'favorite_color' is not defined
02365     TestResults(failed=1, attempted=2)
02366     >>> doctest.master = None  # Reset master.
02367 
02368 The optional keyword argument `raise_on_error` can be used to raise an
02369 exception on the first error (which may be useful for postmortem
02370 debugging):
02371 
02372     >>> doctest.testfile('test_doctest.txt', raise_on_error=True)
02373     ... # doctest: +ELLIPSIS
02374     Traceback (most recent call last):
02375     doctest.UnexpectedException: ...
02376     >>> doctest.master = None  # Reset master.
02377 
02378 If the tests contain non-ASCII characters, the tests might fail, since
02379 it's unknown which encoding is used. The encoding can be specified
02380 using the optional keyword argument `encoding`:
02381 
02382     >>> doctest.testfile('test_doctest4.txt', encoding='latin-1') # doctest: +ELLIPSIS
02383     **********************************************************************
02384     File "...", line 7, in test_doctest4.txt
02385     Failed example:
02386         '...'
02387     Expected:
02388         'f\xf6\xf6'
02389     Got:
02390         'f\xc3\xb6\xc3\xb6'
02391     **********************************************************************
02392     ...
02393     **********************************************************************
02394     1 items had failures:
02395        2 of   2 in test_doctest4.txt
02396     ***Test Failed*** 2 failures.
02397     TestResults(failed=2, attempted=2)
02398     >>> doctest.master = None  # Reset master.
02399 
02400     >>> doctest.testfile('test_doctest4.txt', encoding='utf-8')
02401     TestResults(failed=0, attempted=2)
02402     >>> doctest.master = None  # Reset master.
02403 
02404 Test the verbose output:
02405 
02406     >>> doctest.testfile('test_doctest4.txt', encoding='utf-8', verbose=True)
02407     Trying:
02408         'föö'
02409     Expecting:
02410         'f\xf6\xf6'
02411     ok
02412     Trying:
02413         'bąr'
02414     Expecting:
02415         'b\u0105r'
02416     ok
02417     1 items passed all tests:
02418        2 tests in test_doctest4.txt
02419     2 tests in 1 items.
02420     2 passed and 0 failed.
02421     Test passed.
02422     TestResults(failed=0, attempted=2)
02423     >>> doctest.master = None  # Reset master.
02424     >>> sys.argv = save_argv
02425 """

Definition at line 2426 of file test_doctest.py.

02426 
02427 def test_testmod(): r"""
02428 Tests for the testmod function.  More might be useful, but for now we're just
02429 testing the case raised by Issue 6195, where trying to doctest a C module would
02430 fail with a UnicodeDecodeError because doctest tried to read the "source" lines
02431 out of the binary module.
02432 
02433     >>> import unicodedata
02434     >>> doctest.testmod(unicodedata, verbose=False)
02435     TestResults(failed=0, attempted=0)
02436 """
02437 
02438 try:
    os.fsencode("foo-bär@baz.py")

Definition at line 1619 of file test_doctest.py.

01619 
01620 def test_testsource(): r"""
01621 Unit tests for `testsource()`.
01622 
01623 The testsource() function takes a module and a name, finds the (first)
01624 test with that name in that module, and converts it to a script. The
01625 example code is converted to regular Python code.  The surrounding
01626 words and expected output are converted to comments:
01627 
01628     >>> import test.test_doctest
01629     >>> name = 'test.test_doctest.sample_func'
01630     >>> print(doctest.testsource(test.test_doctest, name))
01631     # Blah blah
01632     #
01633     print(sample_func(22))
01634     # Expected:
01635     ## 44
01636     #
01637     # Yee ha!
01638     <BLANKLINE>
01639 
01640     >>> name = 'test.test_doctest.SampleNewStyleClass'
01641     >>> print(doctest.testsource(test.test_doctest, name))
01642     print('1\n2\n3')
01643     # Expected:
01644     ## 1
01645     ## 2
01646     ## 3
01647     <BLANKLINE>
01648 
01649     >>> name = 'test.test_doctest.SampleClass.a_classmethod'
01650     >>> print(doctest.testsource(test.test_doctest, name))
01651     print(SampleClass.a_classmethod(10))
01652     # Expected:
01653     ## 12
01654     print(SampleClass(0).a_classmethod(10))
01655     # Expected:
01656     ## 12
01657     <BLANKLINE>
01658 """

Trailing spaces in expected output are significant:

  >>> x, y = 'foo', ''
  >>> print(x, y)
  foo \n

Definition at line 2165 of file test_doctest.py.

02165 
02166 def test_trailing_space_in_test():
02167     """
02168     Trailing spaces in expected output are significant:
02169 
02170       >>> x, y = 'foo', ''
02171       >>> print(x, y)
02172       foo \n
02173     """
02174 

Check doctest with a non-ascii filename:

>>> doc = '''
... >>> raise Exception('clé')
... '''
...
>>> parser = doctest.DocTestParser()
>>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
>>> test
<DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
>>> runner = doctest.DocTestRunner(verbose=False)
>>> runner.run(test) # doctest: +ELLIPSIS
**********************************************************************
File "foo-bär@baz.py", line 2, in foo-bär@baz
Failed example:
    raise Exception('clé')
Exception raised:
    Traceback (most recent call last):
      File ...
        compileflags, 1), test.globs)
      File "<doctest foo-bär@baz[0]>", line 1, in <module>
        raise Exception('clé')
    Exception: clé
TestResults(failed=1, attempted=1)

Definition at line 2443 of file test_doctest.py.

02443 
02444     def test_unicode(): """
02445 Check doctest with a non-ascii filename:
02446 
02447     >>> doc = '''
02448     ... >>> raise Exception('clé')
02449     ... '''
02450     ...
02451     >>> parser = doctest.DocTestParser()
02452     >>> test = parser.get_doctest(doc, {}, "foo-bär@baz", "foo-bär@baz.py", 0)
02453     >>> test
02454     <DocTest foo-bär@baz from foo-bär@baz.py:0 (1 example)>
02455     >>> runner = doctest.DocTestRunner(verbose=False)
02456     >>> runner.run(test) # doctest: +ELLIPSIS
02457     **********************************************************************
02458     File "foo-bär@baz.py", line 2, in foo-bär@baz
02459     Failed example:
02460         raise Exception('clé')
02461     Exception raised:
02462         Traceback (most recent call last):
02463           File ...
02464             compileflags, 1), test.globs)
02465           File "<doctest foo-bär@baz[0]>", line 1, in <module>
02466             raise Exception('clé')
02467         Exception: clé
02468     TestResults(failed=1, attempted=1)
02469     """

Default unittest reporting flags can be set to control reporting

Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
only the first failure of each test.  First, we'll look at the
output without the flag.  The file test_doctest.txt file has two
tests. They both fail if blank lines are disabled:

  >>> suite = doctest.DocFileSuite('test_doctest.txt',
  ...                          optionflags=doctest.DONT_ACCEPT_BLANKLINE)
  >>> import unittest
  >>> result = suite.run(unittest.TestResult())
  >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
  Traceback ...
  Failed example:
      favorite_color
  ...
  Failed example:
      if 1:
  ...

Note that we see both failures displayed.

  >>> old = doctest.set_unittest_reportflags(
  ...    doctest.REPORT_ONLY_FIRST_FAILURE)

Now, when we run the test:

  >>> result = suite.run(unittest.TestResult())
  >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
  Traceback ...
  Failed example:
      favorite_color
  Exception raised:
      ...
      NameError: name 'favorite_color' is not defined
  <BLANKLINE>
  <BLANKLINE>

We get only the first failure.

If we give any reporting options when we set up the tests,
however:

  >>> suite = doctest.DocFileSuite('test_doctest.txt',
  ...     optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)

Then the default eporting options are ignored:

  >>> result = suite.run(unittest.TestResult())
  >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
  Traceback ...
  Failed example:
      favorite_color
  ...
  Failed example:
      if 1:
         print('a')
         print()
         print('b')
  Differences (ndiff with -expected +actual):
        a
      - <BLANKLINE>
      +
        b
  <BLANKLINE>
  <BLANKLINE>


Test runners can restore the formatting flags after they run:

  >>> ignored = doctest.set_unittest_reportflags(old)

Definition at line 2175 of file test_doctest.py.

02175 
02176 def test_unittest_reportflags():
02177     """Default unittest reporting flags can be set to control reporting
02178 
02179     Here, we'll set the REPORT_ONLY_FIRST_FAILURE option so we see
02180     only the first failure of each test.  First, we'll look at the
02181     output without the flag.  The file test_doctest.txt file has two
02182     tests. They both fail if blank lines are disabled:
02183 
02184       >>> suite = doctest.DocFileSuite('test_doctest.txt',
02185       ...                          optionflags=doctest.DONT_ACCEPT_BLANKLINE)
02186       >>> import unittest
02187       >>> result = suite.run(unittest.TestResult())
02188       >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
02189       Traceback ...
02190       Failed example:
02191           favorite_color
02192       ...
02193       Failed example:
02194           if 1:
02195       ...
02196 
02197     Note that we see both failures displayed.
02198 
02199       >>> old = doctest.set_unittest_reportflags(
02200       ...    doctest.REPORT_ONLY_FIRST_FAILURE)
02201 
02202     Now, when we run the test:
02203 
02204       >>> result = suite.run(unittest.TestResult())
02205       >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
02206       Traceback ...
02207       Failed example:
02208           favorite_color
02209       Exception raised:
02210           ...
02211           NameError: name 'favorite_color' is not defined
02212       <BLANKLINE>
02213       <BLANKLINE>
02214 
02215     We get only the first failure.
02216 
02217     If we give any reporting options when we set up the tests,
02218     however:
02219 
02220       >>> suite = doctest.DocFileSuite('test_doctest.txt',
02221       ...     optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF)
02222 
02223     Then the default eporting options are ignored:
02224 
02225       >>> result = suite.run(unittest.TestResult())
02226       >>> print(result.failures[0][1]) # doctest: +ELLIPSIS
02227       Traceback ...
02228       Failed example:
02229           favorite_color
02230       ...
02231       Failed example:
02232           if 1:
02233              print('a')
02234              print()
02235              print('b')
02236       Differences (ndiff with -expected +actual):
02237             a
02238           - <BLANKLINE>
02239           +
02240             b
02241       <BLANKLINE>
02242       <BLANKLINE>
02243 
02244 
02245     Test runners can restore the formatting flags after they run:
02246 
02247       >>> ignored = doctest.set_unittest_reportflags(old)
02248 
02249     """