Back to index

python3.2  3.2.2
Classes | Functions | Variables
doctest Namespace Reference

Classes

class  _SpoofOut
class  _OutputRedirectingPdb
class  Example
class  DocTest
class  DocTestParser
class  DocTestFinder
class  DocTestRunner
class  OutputChecker
class  DocTestFailure
class  UnexpectedException
class  DebugRunner
class  DocTestCase
class  SkipDocTestCase
class  DocFileCase
class  _TestClass

Functions

def register_optionflag
def _extract_future_flags
 Table of Contents.
def _normalize_module
def _load_testfile
def _indent
def _exception_traceback
def _ellipsis_match
def _comment_line
def _module_relative_path
def testmod
def testfile
def run_docstring_examples
def set_unittest_reportflags
def DocTestSuite
def DocFileTest
def DocFileSuite
def script_from_examples
def testsource
def debug_src
def debug_script
def debug
def _test

Variables

string __docformat__ = 'reStructuredText en'
list __all__
tuple TestResults = namedtuple('TestResults', 'failed attempted')
dictionary OPTIONFLAGS_BY_NAME = {}
tuple DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
tuple DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
tuple NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
tuple ELLIPSIS = register_optionflag('ELLIPSIS')
tuple SKIP = register_optionflag('SKIP')
tuple IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
tuple COMPARISON_FLAGS
tuple REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
tuple REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
tuple REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
tuple REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
tuple REPORTING_FLAGS
string BLANKLINE_MARKER = '<BLANKLINE>'
string ELLIPSIS_MARKER = '...'
 master = None
int _unittest_reportflags = 0
dictionary __test__

Function Documentation

def doctest._comment_line (   line) [private]

Definition at line 309 of file doctest.py.

00309 
00310 def _comment_line(line):
00311     "Return a commented form of the given line"
00312     line = line.rstrip()
00313     if line:
00314         return '# '+line
00315     else:
00316         return '#'

Here is the caller graph for this function:

def doctest._ellipsis_match (   want,
  got 
) [private]
Essentially the only subtle case:
>>> _ellipsis_match('aa...aa', 'aaa')
False

Definition at line 260 of file doctest.py.

00260 
00261 def _ellipsis_match(want, got):
00262     """
00263     Essentially the only subtle case:
00264     >>> _ellipsis_match('aa...aa', 'aaa')
00265     False
00266     """
00267     if ELLIPSIS_MARKER not in want:
00268         return want == got
00269 
00270     # Find "the real" strings.
00271     ws = want.split(ELLIPSIS_MARKER)
00272     assert len(ws) >= 2
00273 
00274     # Deal with exact matches possibly needed at one or both ends.
00275     startpos, endpos = 0, len(got)
00276     w = ws[0]
00277     if w:   # starts with exact match
00278         if got.startswith(w):
00279             startpos = len(w)
00280             del ws[0]
00281         else:
00282             return False
00283     w = ws[-1]
00284     if w:   # ends with exact match
00285         if got.endswith(w):
00286             endpos -= len(w)
00287             del ws[-1]
00288         else:
00289             return False
00290 
00291     if startpos > endpos:
00292         # Exact end matches required more characters than we have, as in
00293         # _ellipsis_match('aa...aa', 'aaa')
00294         return False
00295 
00296     # For the rest, we only need to find the leftmost non-overlapping
00297     # match for each piece.  If there's no overall match that way alone,
00298     # there's no overall match period.
00299     for w in ws:
00300         # w may be '' at times, if there are consecutive ellipses, or
00301         # due to an ellipsis at the start or end of `want`.  That's OK.
00302         # Search for an empty string succeeds, and doesn't change startpos.
00303         startpos = got.find(w, startpos, endpos)
00304         if startpos < 0:
00305             return False
00306         startpos += len(w)
00307 
00308     return True

Here is the caller graph for this function:

def doctest._exception_traceback (   exc_info) [private]
Return a string containing a traceback message for the given
exc_info tuple (as returned by sys.exc_info()).

Definition at line 233 of file doctest.py.

00233 
00234 def _exception_traceback(exc_info):
00235     """
00236     Return a string containing a traceback message for the given
00237     exc_info tuple (as returned by sys.exc_info()).
00238     """
00239     # Get a traceback message.
00240     excout = StringIO()
00241     exc_type, exc_val, exc_tb = exc_info
00242     traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
00243     return excout.getvalue()
00244 
# Override some StringIO methods.

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest._extract_future_flags (   globs) [private]

Table of Contents.

  1. Utility Functions
  2. Example & DocTest -- store test cases
  3. DocTest Parser -- extracts examples from strings
  4. DocTest Finder -- extracts test cases from objects
  5. DocTest Runner -- runs test cases
  6. Test Functions -- convenient wrappers for testing
  7. Unittest Support
  8. Debugging Support
  9. Example Usage

Utility Functions

Return the compiler-flags associated with the future features that
have been imported into the given namespace (globs).

Definition at line 180 of file doctest.py.

00180 
00181 def _extract_future_flags(globs):
00182     """
00183     Return the compiler-flags associated with the future features that
00184     have been imported into the given namespace (globs).
00185     """
00186     flags = 0
00187     for fname in __future__.all_feature_names:
00188         feature = globs.get(fname, None)
00189         if feature is getattr(__future__, fname):
00190             flags |= feature.compiler_flag
00191     return flags

Here is the call graph for this function:

def doctest._indent (   s,
  indent = 4 
) [private]
Add the given number of space characters to the beginning of
every non-blank line in `s`, and return the result.

Definition at line 225 of file doctest.py.

00225 
00226 def _indent(s, indent=4):
00227     """
00228     Add the given number of space characters to the beginning of
00229     every non-blank line in `s`, and return the result.
00230     """
00231     # This regexp matches the start of non-blank lines:
00232     return re.sub('(?m)^(?!$)', indent*' ', s)

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest._load_testfile (   filename,
  package,
  module_relative,
  encoding 
) [private]

Definition at line 211 of file doctest.py.

00211 
00212 def _load_testfile(filename, package, module_relative, encoding):
00213     if module_relative:
00214         package = _normalize_module(package, 3)
00215         filename = _module_relative_path(package, filename)
00216         if hasattr(package, '__loader__'):
00217             if hasattr(package.__loader__, 'get_data'):
00218                 file_contents = package.__loader__.get_data(filename)
00219                 file_contents = file_contents.decode(encoding)
00220                 # get_data() opens files as 'rb', so one must do the equivalent
00221                 # conversion as universal newlines would do.
00222                 return file_contents.replace(os.linesep, '\n'), filename
00223     with open(filename, encoding=encoding) as f:
00224         return f.read(), filename

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest._module_relative_path (   module,
  path 
) [private]

Definition at line 354 of file doctest.py.

00354 
00355 def _module_relative_path(module, path):
00356     if not inspect.ismodule(module):
00357         raise TypeError('Expected a module: %r' % module)
00358     if path.startswith('/'):
00359         raise ValueError('Module-relative files may not have absolute paths')
00360 
00361     # Find the base directory for the path.
00362     if hasattr(module, '__file__'):
00363         # A normal module/package
00364         basedir = os.path.split(module.__file__)[0]
00365     elif module.__name__ == '__main__':
00366         # An interactive session.
00367         if len(sys.argv)>0 and sys.argv[0] != '':
00368             basedir = os.path.split(sys.argv[0])[0]
00369         else:
00370             basedir = os.curdir
00371     else:
00372         # A module w/o __file__ (this includes builtins)
00373         raise ValueError("Can't resolve paths relative to the module " +
00374                          module + " (it has no __file__)")
00375 
00376     # Combine the base directory and the path.
00377     return os.path.join(basedir, *(path.split('/')))

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest._normalize_module (   module,
  depth = 2 
) [private]
Return the module specified by `module`.  In particular:
  - If `module` is a module, then return module.
  - If `module` is a string, then import and return the
    module with that name.
  - If `module` is None, then return the calling module.
    The calling module is assumed to be the module of
    the stack frame at the given depth in the call stack.

Definition at line 192 of file doctest.py.

00192 
00193 def _normalize_module(module, depth=2):
00194     """
00195     Return the module specified by `module`.  In particular:
00196       - If `module` is a module, then return module.
00197       - If `module` is a string, then import and return the
00198         module with that name.
00199       - If `module` is None, then return the calling module.
00200         The calling module is assumed to be the module of
00201         the stack frame at the given depth in the call stack.
00202     """
00203     if inspect.ismodule(module):
00204         return module
00205     elif isinstance(module, str):
00206         return __import__(module, globals(), locals(), ["*"])
00207     elif module is None:
00208         return sys.modules[sys._getframe(depth).f_globals['__name__']]
00209     else:
00210         raise TypeError("Expected a module, string, or None")

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest._test ( ) [private]

Definition at line 2642 of file doctest.py.

02642 
02643 def _test():
02644     testfiles = [arg for arg in sys.argv[1:] if arg and arg[0] != '-']
02645     if not testfiles:
02646         name = os.path.basename(sys.argv[0])
02647         if '__loader__' in globals():          # python -m
02648             name, _ = os.path.splitext(name)
02649         print("usage: {0} [-v] file ...".format(name))
02650         return 2
02651     for filename in testfiles:
02652         if filename.endswith(".py"):
02653             # It is a module -- insert its dir into sys.path and try to
02654             # import it. If it is part of a package, that possibly
02655             # won't work because of package imports.
02656             dirname, filename = os.path.split(filename)
02657             sys.path.insert(0, dirname)
02658             m = __import__(filename[:-3])
02659             del sys.path[0]
02660             failures, _ = testmod(m)
02661         else:
02662             failures, _ = testfile(filename, module_relative=False)
02663         if failures:
02664             return 1
02665     return 0
02666 

Here is the call graph for this function:

def doctest.debug (   module,
  name,
  pm = False 
)
Debug a single doctest docstring.

Provide the module (or dotted name of the module) containing the
test to be debugged and the name (within the module) of the object
with the docstring with tests to be debugged.

Definition at line 2533 of file doctest.py.

02533 
02534 def debug(module, name, pm=False):
02535     """Debug a single doctest docstring.
02536 
02537     Provide the module (or dotted name of the module) containing the
02538     test to be debugged and the name (within the module) of the object
02539     with the docstring with tests to be debugged.
02540     """
02541     module = _normalize_module(module)
02542     testsrc = testsource(module, name)
02543     debug_script(testsrc, pm, module.__dict__)

Here is the call graph for this function:

def doctest.debug_script (   src,
  pm = False,
  globs = None 
)

Definition at line 2513 of file doctest.py.

02513 
02514 def debug_script(src, pm=False, globs=None):
02515     "Debug a test script.  `src` is the script, as a string."
02516     import pdb
02517 
02518     if globs:
02519         globs = globs.copy()
02520     else:
02521         globs = {}
02522 
02523     if pm:
02524         try:
02525             exec(src, globs, globs)
02526         except:
02527             print(sys.exc_info()[1])
02528             p = pdb.Pdb(nosigint=True)
02529             p.reset()
02530             p.interaction(None, sys.exc_info()[2])
02531     else:
02532         pdb.Pdb(nosigint=True).run("exec(%r)" % src, globs, globs)

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest.debug_src (   src,
  pm = False,
  globs = None 
)
Debug a single doctest docstring, in argument `src`'

Definition at line 2508 of file doctest.py.

02508 
02509 def debug_src(src, pm=False, globs=None):
02510     """Debug a single doctest docstring, in argument `src`'"""
02511     testsrc = script_from_examples(src)
02512     debug_script(testsrc, pm, globs)

Here is the call graph for this function:

def doctest.DocFileSuite (   paths,
  kw 
)
A unittest suite for one or more doctest files.

The path to each doctest file is given as a string; the
interpretation of that string depends on the keyword argument
"module_relative".

A number of options may be provided as keyword arguments:

module_relative
  If "module_relative" is True, then the given file paths are
  interpreted as os-independent module-relative paths.  By
  default, these paths are relative to the calling module's
  directory; but if the "package" argument is specified, then
  they are relative to that package.  To ensure os-independence,
  "filename" should use "/" characters to separate path
  segments, and may not be an absolute path (i.e., it may not
  begin with "/").

  If "module_relative" is False, then the given file paths are
  interpreted as os-specific paths.  These paths may be absolute
  or relative (to the current working directory).

package
  A Python package or the name of a Python package whose directory
  should be used as the base directory for module relative paths.
  If "package" is not specified, then the calling module's
  directory is used as the base directory for module relative
  filenames.  It is an error to specify "package" if
  "module_relative" is False.

setUp
  A set-up function.  This is called before running the
  tests in each file. The setUp function will be passed a DocTest
  object.  The setUp function can access the test globals as the
  globs attribute of the test passed.

tearDown
  A tear-down function.  This is called after running the
  tests in each file.  The tearDown function will be passed a DocTest
  object.  The tearDown function can access the test globals as the
  globs attribute of the test passed.

globs
  A dictionary containing initial global variables for the tests.

optionflags
  A set of doctest option flags expressed as an integer.

parser
  A DocTestParser (or subclass) that should be used to extract
  tests from the files.

encoding
  An encoding that will be used to convert the files to unicode.

Definition at line 2337 of file doctest.py.

02337 
02338 def DocFileSuite(*paths, **kw):
02339     """A unittest suite for one or more doctest files.
02340 
02341     The path to each doctest file is given as a string; the
02342     interpretation of that string depends on the keyword argument
02343     "module_relative".
02344 
02345     A number of options may be provided as keyword arguments:
02346 
02347     module_relative
02348       If "module_relative" is True, then the given file paths are
02349       interpreted as os-independent module-relative paths.  By
02350       default, these paths are relative to the calling module's
02351       directory; but if the "package" argument is specified, then
02352       they are relative to that package.  To ensure os-independence,
02353       "filename" should use "/" characters to separate path
02354       segments, and may not be an absolute path (i.e., it may not
02355       begin with "/").
02356 
02357       If "module_relative" is False, then the given file paths are
02358       interpreted as os-specific paths.  These paths may be absolute
02359       or relative (to the current working directory).
02360 
02361     package
02362       A Python package or the name of a Python package whose directory
02363       should be used as the base directory for module relative paths.
02364       If "package" is not specified, then the calling module's
02365       directory is used as the base directory for module relative
02366       filenames.  It is an error to specify "package" if
02367       "module_relative" is False.
02368 
02369     setUp
02370       A set-up function.  This is called before running the
02371       tests in each file. The setUp function will be passed a DocTest
02372       object.  The setUp function can access the test globals as the
02373       globs attribute of the test passed.
02374 
02375     tearDown
02376       A tear-down function.  This is called after running the
02377       tests in each file.  The tearDown function will be passed a DocTest
02378       object.  The tearDown function can access the test globals as the
02379       globs attribute of the test passed.
02380 
02381     globs
02382       A dictionary containing initial global variables for the tests.
02383 
02384     optionflags
02385       A set of doctest option flags expressed as an integer.
02386 
02387     parser
02388       A DocTestParser (or subclass) that should be used to extract
02389       tests from the files.
02390 
02391     encoding
02392       An encoding that will be used to convert the files to unicode.
02393     """
02394     suite = unittest.TestSuite()
02395 
02396     # We do this here so that _normalize_module is called at the right
02397     # level.  If it were called in DocFileTest, then this function
02398     # would be the caller and we might guess the package incorrectly.
02399     if kw.get('module_relative', True):
02400         kw['package'] = _normalize_module(kw.get('package'))
02401 
02402     for path in paths:
02403         suite.addTest(DocFileTest(path, **kw))
02404 
02405     return suite

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest.DocFileTest (   path,
  module_relative = True,
  package = None,
  globs = None,
  parser = DocTestParser(),
  encoding = None,
  options 
)

Definition at line 2313 of file doctest.py.

02313 
02314                 encoding=None, **options):
02315     if globs is None:
02316         globs = {}
02317     else:
02318         globs = globs.copy()
02319 
02320     if package and not module_relative:
02321         raise ValueError("Package may only be specified for module-"
02322                          "relative paths.")
02323 
02324     # Relativize the path.
02325     doc, path = _load_testfile(path, package, module_relative,
02326                                encoding or "utf-8")
02327 
02328     if "__file__" not in globs:
02329         globs["__file__"] = path
02330 
02331     # Find the file and read it.
02332     name = os.path.basename(path)
02333 
02334     # Convert it to a test, and wrap it in a DocFileCase.
02335     test = parser.get_doctest(doc, globs, name, path, 0)
02336     return DocFileCase(test, **options)

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest.DocTestSuite (   module = None,
  globs = None,
  extraglobs = None,
  test_finder = None,
  options 
)
Convert doctest tests for a module to a unittest test suite.

This converts each documentation string in a module that
contains doctest tests to a unittest test case.  If any of the
tests in a doc string fail, then the test case fails.  An exception
is raised showing the name of the file containing the test and a
(sometimes approximate) line number.

The `module` argument provides the module to be tested.  The argument
can be either a module or a module name.

If no argument is given, the calling module is used.

A number of options may be provided as keyword arguments:

setUp
  A set-up function.  This is called before running the
  tests in each file. The setUp function will be passed a DocTest
  object.  The setUp function can access the test globals as the
  globs attribute of the test passed.

tearDown
  A tear-down function.  This is called after running the
  tests in each file.  The tearDown function will be passed a DocTest
  object.  The tearDown function can access the test globals as the
  globs attribute of the test passed.

globs
  A dictionary containing initial global variables for the tests.

optionflags
   A set of doctest option flags expressed as an integer.

Definition at line 2230 of file doctest.py.

02230 
02231                  **options):
02232     """
02233     Convert doctest tests for a module to a unittest test suite.
02234 
02235     This converts each documentation string in a module that
02236     contains doctest tests to a unittest test case.  If any of the
02237     tests in a doc string fail, then the test case fails.  An exception
02238     is raised showing the name of the file containing the test and a
02239     (sometimes approximate) line number.
02240 
02241     The `module` argument provides the module to be tested.  The argument
02242     can be either a module or a module name.
02243 
02244     If no argument is given, the calling module is used.
02245 
02246     A number of options may be provided as keyword arguments:
02247 
02248     setUp
02249       A set-up function.  This is called before running the
02250       tests in each file. The setUp function will be passed a DocTest
02251       object.  The setUp function can access the test globals as the
02252       globs attribute of the test passed.
02253 
02254     tearDown
02255       A tear-down function.  This is called after running the
02256       tests in each file.  The tearDown function will be passed a DocTest
02257       object.  The tearDown function can access the test globals as the
02258       globs attribute of the test passed.
02259 
02260     globs
02261       A dictionary containing initial global variables for the tests.
02262 
02263     optionflags
02264        A set of doctest option flags expressed as an integer.
02265     """
02266 
02267     if test_finder is None:
02268         test_finder = DocTestFinder()
02269 
02270     module = _normalize_module(module)
02271     tests = test_finder.find(module, globs=globs, extraglobs=extraglobs)
02272 
02273     if not tests and sys.flags.optimize >=2:
02274         # Skip doctests when running with -O2
02275         suite = unittest.TestSuite()
02276         suite.addTest(SkipDocTestCase())
02277         return suite
02278     elif not tests:
02279         # Why do we want to do this? Because it reveals a bug that might
02280         # otherwise be hidden.
02281         raise ValueError(module, "has no tests")
02282 
02283     tests.sort()
02284     suite = unittest.TestSuite()
02285 
02286     for test in tests:
02287         if len(test.examples) == 0:
02288             continue
02289         if not test.filename:
02290             filename = module.__file__
02291             if filename[-4:] in (".pyc", ".pyo"):
02292                 filename = filename[:-1]
02293             test.filename = filename
02294         suite.addTest(DocTestCase(test, **options))
02295 
02296     return suite

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 131 of file doctest.py.

00131 
00132 def register_optionflag(name):
00133     # Create a new flag unless `name` is already known.
00134     return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))

def doctest.run_docstring_examples (   f,
  globs,
  verbose = False,
  name = "NoName",
  compileflags = None,
  optionflags = 0 
)
Test examples in the given object's docstring (`f`), using `globs`
as globals.  Optional argument `name` is used in failure messages.
If the optional argument `verbose` is true, then generate output
even if there are no failures.

`compileflags` gives the set of flags that should be used by the
Python compiler when running the examples.  If not specified, then
it will default to the set of future-import flags that apply to
`globs`.

Optional keyword arg `optionflags` specifies options for the
testing and output.  See the documentation for `testmod` for more
information.

Definition at line 2006 of file doctest.py.

02006 
02007                            compileflags=None, optionflags=0):
02008     """
02009     Test examples in the given object's docstring (`f`), using `globs`
02010     as globals.  Optional argument `name` is used in failure messages.
02011     If the optional argument `verbose` is true, then generate output
02012     even if there are no failures.
02013 
02014     `compileflags` gives the set of flags that should be used by the
02015     Python compiler when running the examples.  If not specified, then
02016     it will default to the set of future-import flags that apply to
02017     `globs`.
02018 
02019     Optional keyword arg `optionflags` specifies options for the
02020     testing and output.  See the documentation for `testmod` for more
02021     information.
02022     """
02023     # Find, parse, and run all tests in the given module.
02024     finder = DocTestFinder(verbose=verbose, recurse=False)
02025     runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
02026     for test in finder.find(f, name, globs=globs):
02027         runner.run(test, compileflags=compileflags)

Here is the caller graph for this function:

  1. Debugging Support

Definition at line 2410 of file doctest.py.

02410 
02411 def script_from_examples(s):
02412     r"""Extract script from text with examples.
02413 
02414        Converts text with examples to a Python script.  Example input is
02415        converted to regular code.  Example output and all other words
02416        are converted to comments:
02417 
02418        >>> text = '''
02419        ...       Here are examples of simple math.
02420        ...
02421        ...           Python has super accurate integer addition
02422        ...
02423        ...           >>> 2 + 2
02424        ...           5
02425        ...
02426        ...           And very friendly error messages:
02427        ...
02428        ...           >>> 1/0
02429        ...           To Infinity
02430        ...           And
02431        ...           Beyond
02432        ...
02433        ...           You can use logic if you want:
02434        ...
02435        ...           >>> if 0:
02436        ...           ...    blah
02437        ...           ...    blah
02438        ...           ...
02439        ...
02440        ...           Ho hum
02441        ...           '''
02442 
02443        >>> print(script_from_examples(text))
02444        # Here are examples of simple math.
02445        #
02446        #     Python has super accurate integer addition
02447        #
02448        2 + 2
02449        # Expected:
02450        ## 5
02451        #
02452        #     And very friendly error messages:
02453        #
02454        1/0
02455        # Expected:
02456        ## To Infinity
02457        ## And
02458        ## Beyond
02459        #
02460        #     You can use logic if you want:
02461        #
02462        if 0:
02463           blah
02464           blah
02465        #
02466        #     Ho hum
02467        <BLANKLINE>
02468        """
02469     output = []
02470     for piece in DocTestParser().parse(s):
02471         if isinstance(piece, Example):
02472             # Add the example's source code (strip trailing NL)
02473             output.append(piece.source[:-1])
02474             # Add the expected output:
02475             want = piece.want
02476             if want:
02477                 output.append('# Expected:')
02478                 output += ['## '+l for l in want.split('\n')[:-1]]
02479         else:
02480             # Add non-example text.
02481             output += [_comment_line(l)
02482                        for l in piece.split('\n')[:-1]]
02483 
02484     # Trim junk on both ends.
02485     while output and output[-1] == '#':
02486         output.pop()
02487     while output and output[0] == '#':
02488         output.pop(0)
02489     # Combine the output, and return it.
02490     # Add a courtesy newline to prevent exec from choking (see bug #1172785)
02491     return '\n'.join(output) + '\n'

Here is the call graph for this function:

Here is the caller graph for this function:

Sets the unittest option flags.

The old flag is returned so that a runner could restore the old
value if it wished to:

  >>> import doctest
  >>> old = doctest._unittest_reportflags
  >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
  ...                          REPORT_ONLY_FIRST_FAILURE) == old
  True

  >>> doctest._unittest_reportflags == (REPORT_NDIFF |
  ...                                   REPORT_ONLY_FIRST_FAILURE)
  True

Only reporting flags can be set:

  >>> doctest.set_unittest_reportflags(ELLIPSIS)
  Traceback (most recent call last):
  ...
  ValueError: ('Only reporting flags allowed', 8)

  >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
  ...                                   REPORT_ONLY_FIRST_FAILURE)
  True

Definition at line 2034 of file doctest.py.

02034 
02035 def set_unittest_reportflags(flags):
02036     """Sets the unittest option flags.
02037 
02038     The old flag is returned so that a runner could restore the old
02039     value if it wished to:
02040 
02041       >>> import doctest
02042       >>> old = doctest._unittest_reportflags
02043       >>> doctest.set_unittest_reportflags(REPORT_NDIFF |
02044       ...                          REPORT_ONLY_FIRST_FAILURE) == old
02045       True
02046 
02047       >>> doctest._unittest_reportflags == (REPORT_NDIFF |
02048       ...                                   REPORT_ONLY_FIRST_FAILURE)
02049       True
02050 
02051     Only reporting flags can be set:
02052 
02053       >>> doctest.set_unittest_reportflags(ELLIPSIS)
02054       Traceback (most recent call last):
02055       ...
02056       ValueError: ('Only reporting flags allowed', 8)
02057 
02058       >>> doctest.set_unittest_reportflags(old) == (REPORT_NDIFF |
02059       ...                                   REPORT_ONLY_FIRST_FAILURE)
02060       True
02061     """
02062     global _unittest_reportflags
02063 
02064     if (flags & REPORTING_FLAGS) != flags:
02065         raise ValueError("Only reporting flags allowed", flags)
02066     old = _unittest_reportflags
02067     _unittest_reportflags = flags
02068     return old
02069 

def doctest.testfile (   filename,
  module_relative = True,
  name = None,
  package = None,
  globs = None,
  verbose = None,
  report = True,
  optionflags = 0,
  extraglobs = None,
  raise_on_error = False,
  parser = DocTestParser(),
  encoding = None 
)
Test examples in the given file.  Return (#failures, #tests).

Optional keyword arg "module_relative" specifies how filenames
should be interpreted:

  - If "module_relative" is True (the default), then "filename"
     specifies a module-relative path.  By default, this path is
     relative to the calling module's directory; but if the
     "package" argument is specified, then it is relative to that
     package.  To ensure os-independence, "filename" should use
     "/" characters to separate path segments, and should not
     be an absolute path (i.e., it may not begin with "/").

  - If "module_relative" is False, then "filename" specifies an
    os-specific path.  The path may be absolute or relative (to
    the current working directory).

Optional keyword arg "name" gives the name of the test; by default
use the file's basename.

Optional keyword argument "package" is a Python package or the
name of a Python package whose directory should be used as the
base directory for a module relative filename.  If no package is
specified, then the calling module's directory is used as the base
directory for module relative filenames.  It is an error to
specify "package" if "module_relative" is False.

Optional keyword arg "globs" gives a dict to be used as the globals
when executing examples; by default, use {}.  A copy of this dict
is actually used for each docstring, so that each docstring's
examples start with a clean slate.

Optional keyword arg "extraglobs" gives a dictionary that should be
merged into the globals that are used to execute examples.  By
default, no extra globals are used.

Optional keyword arg "verbose" prints lots of stuff if true, prints
only failures if false; by default, it's true iff "-v" is in sys.argv.

Optional keyword arg "report" prints a summary at the end when true,
else prints nothing at the end.  In verbose mode, the summary is
detailed, else very brief (in fact, empty if all tests passed).

Optional keyword arg "optionflags" or's together module constants,
and defaults to 0.  Possible values (see the docs for details):

    DONT_ACCEPT_TRUE_FOR_1
    DONT_ACCEPT_BLANKLINE
    NORMALIZE_WHITESPACE
    ELLIPSIS
    SKIP
    IGNORE_EXCEPTION_DETAIL
    REPORT_UDIFF
    REPORT_CDIFF
    REPORT_NDIFF
    REPORT_ONLY_FIRST_FAILURE

Optional keyword arg "raise_on_error" raises an exception on the
first unexpected exception or failure. This allows failures to be
post-mortem debugged.

Optional keyword arg "parser" specifies a DocTestParser (or
subclass) that should be used to extract tests from the files.

Optional keyword arg "encoding" specifies an encoding that should
be used to convert the file to unicode.

Advanced tomfoolery:  testmod runs methods of a local instance of
class doctest.Tester, then merges the results into (or creates)
global Tester instance doctest.master.  Methods of doctest.master
can be called directly too, if you want to do something unusual.
Passing report=0 to testmod is especially useful then, to delay
displaying a summary.  Invoke doctest.master.summarize(verbose)
when you're done fiddling.

Definition at line 1885 of file doctest.py.

01885 
01886              encoding=None):
01887     """
01888     Test examples in the given file.  Return (#failures, #tests).
01889 
01890     Optional keyword arg "module_relative" specifies how filenames
01891     should be interpreted:
01892 
01893       - If "module_relative" is True (the default), then "filename"
01894          specifies a module-relative path.  By default, this path is
01895          relative to the calling module's directory; but if the
01896          "package" argument is specified, then it is relative to that
01897          package.  To ensure os-independence, "filename" should use
01898          "/" characters to separate path segments, and should not
01899          be an absolute path (i.e., it may not begin with "/").
01900 
01901       - If "module_relative" is False, then "filename" specifies an
01902         os-specific path.  The path may be absolute or relative (to
01903         the current working directory).
01904 
01905     Optional keyword arg "name" gives the name of the test; by default
01906     use the file's basename.
01907 
01908     Optional keyword argument "package" is a Python package or the
01909     name of a Python package whose directory should be used as the
01910     base directory for a module relative filename.  If no package is
01911     specified, then the calling module's directory is used as the base
01912     directory for module relative filenames.  It is an error to
01913     specify "package" if "module_relative" is False.
01914 
01915     Optional keyword arg "globs" gives a dict to be used as the globals
01916     when executing examples; by default, use {}.  A copy of this dict
01917     is actually used for each docstring, so that each docstring's
01918     examples start with a clean slate.
01919 
01920     Optional keyword arg "extraglobs" gives a dictionary that should be
01921     merged into the globals that are used to execute examples.  By
01922     default, no extra globals are used.
01923 
01924     Optional keyword arg "verbose" prints lots of stuff if true, prints
01925     only failures if false; by default, it's true iff "-v" is in sys.argv.
01926 
01927     Optional keyword arg "report" prints a summary at the end when true,
01928     else prints nothing at the end.  In verbose mode, the summary is
01929     detailed, else very brief (in fact, empty if all tests passed).
01930 
01931     Optional keyword arg "optionflags" or's together module constants,
01932     and defaults to 0.  Possible values (see the docs for details):
01933 
01934         DONT_ACCEPT_TRUE_FOR_1
01935         DONT_ACCEPT_BLANKLINE
01936         NORMALIZE_WHITESPACE
01937         ELLIPSIS
01938         SKIP
01939         IGNORE_EXCEPTION_DETAIL
01940         REPORT_UDIFF
01941         REPORT_CDIFF
01942         REPORT_NDIFF
01943         REPORT_ONLY_FIRST_FAILURE
01944 
01945     Optional keyword arg "raise_on_error" raises an exception on the
01946     first unexpected exception or failure. This allows failures to be
01947     post-mortem debugged.
01948 
01949     Optional keyword arg "parser" specifies a DocTestParser (or
01950     subclass) that should be used to extract tests from the files.
01951 
01952     Optional keyword arg "encoding" specifies an encoding that should
01953     be used to convert the file to unicode.
01954 
01955     Advanced tomfoolery:  testmod runs methods of a local instance of
01956     class doctest.Tester, then merges the results into (or creates)
01957     global Tester instance doctest.master.  Methods of doctest.master
01958     can be called directly too, if you want to do something unusual.
01959     Passing report=0 to testmod is especially useful then, to delay
01960     displaying a summary.  Invoke doctest.master.summarize(verbose)
01961     when you're done fiddling.
01962     """
01963     global master
01964 
01965     if package and not module_relative:
01966         raise ValueError("Package may only be specified for module-"
01967                          "relative paths.")
01968 
01969     # Relativize the path
01970     text, filename = _load_testfile(filename, package, module_relative,
01971                                     encoding or "utf-8")
01972 
01973     # If no name was given, then use the file's name.
01974     if name is None:
01975         name = os.path.basename(filename)
01976 
01977     # Assemble the globals.
01978     if globs is None:
01979         globs = {}
01980     else:
01981         globs = globs.copy()
01982     if extraglobs is not None:
01983         globs.update(extraglobs)
01984     if '__name__' not in globs:
01985         globs['__name__'] = '__main__'
01986 
01987     if raise_on_error:
01988         runner = DebugRunner(verbose=verbose, optionflags=optionflags)
01989     else:
01990         runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
01991 
01992     # Read the file, convert it to a test, and run it.
01993     test = parser.get_doctest(text, globs, name, filename, 0)
01994     runner.run(test)
01995 
01996     if report:
01997         runner.summarize()
01998 
01999     if master is None:
02000         master = runner
02001     else:
02002         master.merge(runner)
02003 
02004     return TestResults(runner.failures, runner.tries)

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest.testmod (   m = None,
  name = None,
  globs = None,
  verbose = None,
  report = True,
  optionflags = 0,
  extraglobs = None,
  raise_on_error = False,
  exclude_empty = False 
)
m=None, name=None, globs=None, verbose=None, report=True,
   optionflags=0, extraglobs=None, raise_on_error=False,
   exclude_empty=False

Test examples in docstrings in functions and classes reachable
from module m (or the current module if m is not supplied), starting
with m.__doc__.

Also test examples reachable from dict m.__test__ if it exists and is
not None.  m.__test__ maps names to functions, classes and strings;
function and class docstrings are tested even if the name is private;
strings are tested directly, as if they were docstrings.

Return (#failures, #tests).

See help(doctest) for an overview.

Optional keyword arg "name" gives the name of the module; by default
use m.__name__.

Optional keyword arg "globs" gives a dict to be used as the globals
when executing examples; by default, use m.__dict__.  A copy of this
dict is actually used for each docstring, so that each docstring's
examples start with a clean slate.

Optional keyword arg "extraglobs" gives a dictionary that should be
merged into the globals that are used to execute examples.  By
default, no extra globals are used.  This is new in 2.4.

Optional keyword arg "verbose" prints lots of stuff if true, prints
only failures if false; by default, it's true iff "-v" is in sys.argv.

Optional keyword arg "report" prints a summary at the end when true,
else prints nothing at the end.  In verbose mode, the summary is
detailed, else very brief (in fact, empty if all tests passed).

Optional keyword arg "optionflags" or's together module constants,
and defaults to 0.  This is new in 2.3.  Possible values (see the
docs for details):

    DONT_ACCEPT_TRUE_FOR_1
    DONT_ACCEPT_BLANKLINE
    NORMALIZE_WHITESPACE
    ELLIPSIS
    SKIP
    IGNORE_EXCEPTION_DETAIL
    REPORT_UDIFF
    REPORT_CDIFF
    REPORT_NDIFF
    REPORT_ONLY_FIRST_FAILURE

Optional keyword arg "raise_on_error" raises an exception on the
first unexpected exception or failure. This allows failures to be
post-mortem debugged.

Advanced tomfoolery:  testmod runs methods of a local instance of
class doctest.Tester, then merges the results into (or creates)
global Tester instance doctest.master.  Methods of doctest.master
can be called directly too, if you want to do something unusual.
Passing report=0 to testmod is especially useful then, to delay
displaying a summary.  Invoke doctest.master.summarize(verbose)
when you're done fiddling.

Definition at line 1780 of file doctest.py.

01780 
01781             raise_on_error=False, exclude_empty=False):
01782     """m=None, name=None, globs=None, verbose=None, report=True,
01783        optionflags=0, extraglobs=None, raise_on_error=False,
01784        exclude_empty=False
01785 
01786     Test examples in docstrings in functions and classes reachable
01787     from module m (or the current module if m is not supplied), starting
01788     with m.__doc__.
01789 
01790     Also test examples reachable from dict m.__test__ if it exists and is
01791     not None.  m.__test__ maps names to functions, classes and strings;
01792     function and class docstrings are tested even if the name is private;
01793     strings are tested directly, as if they were docstrings.
01794 
01795     Return (#failures, #tests).
01796 
01797     See help(doctest) for an overview.
01798 
01799     Optional keyword arg "name" gives the name of the module; by default
01800     use m.__name__.
01801 
01802     Optional keyword arg "globs" gives a dict to be used as the globals
01803     when executing examples; by default, use m.__dict__.  A copy of this
01804     dict is actually used for each docstring, so that each docstring's
01805     examples start with a clean slate.
01806 
01807     Optional keyword arg "extraglobs" gives a dictionary that should be
01808     merged into the globals that are used to execute examples.  By
01809     default, no extra globals are used.  This is new in 2.4.
01810 
01811     Optional keyword arg "verbose" prints lots of stuff if true, prints
01812     only failures if false; by default, it's true iff "-v" is in sys.argv.
01813 
01814     Optional keyword arg "report" prints a summary at the end when true,
01815     else prints nothing at the end.  In verbose mode, the summary is
01816     detailed, else very brief (in fact, empty if all tests passed).
01817 
01818     Optional keyword arg "optionflags" or's together module constants,
01819     and defaults to 0.  This is new in 2.3.  Possible values (see the
01820     docs for details):
01821 
01822         DONT_ACCEPT_TRUE_FOR_1
01823         DONT_ACCEPT_BLANKLINE
01824         NORMALIZE_WHITESPACE
01825         ELLIPSIS
01826         SKIP
01827         IGNORE_EXCEPTION_DETAIL
01828         REPORT_UDIFF
01829         REPORT_CDIFF
01830         REPORT_NDIFF
01831         REPORT_ONLY_FIRST_FAILURE
01832 
01833     Optional keyword arg "raise_on_error" raises an exception on the
01834     first unexpected exception or failure. This allows failures to be
01835     post-mortem debugged.
01836 
01837     Advanced tomfoolery:  testmod runs methods of a local instance of
01838     class doctest.Tester, then merges the results into (or creates)
01839     global Tester instance doctest.master.  Methods of doctest.master
01840     can be called directly too, if you want to do something unusual.
01841     Passing report=0 to testmod is especially useful then, to delay
01842     displaying a summary.  Invoke doctest.master.summarize(verbose)
01843     when you're done fiddling.
01844     """
01845     global master
01846 
01847     # If no module was given, then use __main__.
01848     if m is None:
01849         # DWA - m will still be None if this wasn't invoked from the command
01850         # line, in which case the following TypeError is about as good an error
01851         # as we should expect
01852         m = sys.modules.get('__main__')
01853 
01854     # Check that we were actually given a module.
01855     if not inspect.ismodule(m):
01856         raise TypeError("testmod: module required; %r" % (m,))
01857 
01858     # If no name was given, then use the module's name.
01859     if name is None:
01860         name = m.__name__
01861 
01862     # Find, parse, and run all tests in the given module.
01863     finder = DocTestFinder(exclude_empty=exclude_empty)
01864 
01865     if raise_on_error:
01866         runner = DebugRunner(verbose=verbose, optionflags=optionflags)
01867     else:
01868         runner = DocTestRunner(verbose=verbose, optionflags=optionflags)
01869 
01870     for test in finder.find(m, name, globs=globs, extraglobs=extraglobs):
01871         runner.run(test)
01872 
01873     if report:
01874         runner.summarize()
01875 
01876     if master is None:
01877         master = runner
01878     else:
01879         master.merge(runner)
01880 
01881     return TestResults(runner.failures, runner.tries)

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest.testsource (   module,
  name 
)
Extract the test sources from a doctest docstring as a script.

Provide the module (or dotted name of the module) containing the
test to be debugged and the name (within the module) of the object
with the doc string with tests to be debugged.

Definition at line 2492 of file doctest.py.

02492 
02493 def testsource(module, name):
02494     """Extract the test sources from a doctest docstring as a script.
02495 
02496     Provide the module (or dotted name of the module) containing the
02497     test to be debugged and the name (within the module) of the object
02498     with the doc string with tests to be debugged.
02499     """
02500     module = _normalize_module(module)
02501     tests = DocTestFinder().find(module)
02502     test = [t for t in tests if t.name == name]
02503     if not test:
02504         raise ValueError(name, "not found in tests")
02505     test = test[0]
02506     testsrc = script_from_examples(test.docstring)
02507     return testsrc

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Definition at line 50 of file doctest.py.

string doctest.__docformat__ = 'reStructuredText en'

Definition at line 48 of file doctest.py.

Initial value:
00001 {"_TestClass": _TestClass,
00002             "string": r"""                      Example of a string object, searched as-is.                      >>> x = 1; y = 2                      >>> x + y, x * y                      (3, 2)                      """,
00003 
00004             "bool-int equivalence": r"""                                    In 2.2, boolean expressions displayed                                    0 or 1.  By default, we still accept                                    them.  This can be disabled by passing                                    DONT_ACCEPT_TRUE_FOR_1 to the new                                    optionflags argument.                                    >>> 4 == 4                                    1                                    >>> 4 == 4                                    True                                    >>> 4 > 4                                    0                                    >>> 4 > 4                                    False                                    """,
00005 
00006             "blank lines": r"""                Blank lines can be marked with <BLANKLINE>:                    >>> print('foo\n\nbar\n')                    foo                    <BLANKLINE>                    bar                    <BLANKLINE>            """,
00007 
00008             "ellipsis": r"""                If the ellipsis flag is used, then '...' can be used to                elide substrings in the desired output:                    >>> print(list(range(1000))) #doctest: +ELLIPSIS                    [0, 1, 2, ..., 999]            """,
00009 
00010             "whitespace normalization": r"""                If the whitespace normalization flag is used, then                differences in whitespace are ignored.                    >>> print(list(range(30))) #doctest: +NORMALIZE_WHITESPACE                    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,                     15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,                     27, 28, 29]            """,
00011            }

Definition at line 2591 of file doctest.py.

  1. Unittest Support

Definition at line 2032 of file doctest.py.

Definition at line 160 of file doctest.py.

Initial value:
00001 (DONT_ACCEPT_TRUE_FOR_1 |
00002                     DONT_ACCEPT_BLANKLINE |
00003                     NORMALIZE_WHITESPACE |
00004                     ELLIPSIS |
00005                     SKIP |
00006                     IGNORE_EXCEPTION_DETAIL)

Definition at line 142 of file doctest.py.

Definition at line 136 of file doctest.py.

Definition at line 135 of file doctest.py.

Definition at line 138 of file doctest.py.

Definition at line 161 of file doctest.py.

Definition at line 140 of file doctest.py.

  1. Test Functions

These should be backwards compatible.

Definition at line 1776 of file doctest.py.

Definition at line 137 of file doctest.py.

Definition at line 130 of file doctest.py.

Definition at line 150 of file doctest.py.

Definition at line 151 of file doctest.py.

Definition at line 152 of file doctest.py.

Definition at line 149 of file doctest.py.

Initial value:
00001 (REPORT_UDIFF |
00002                    REPORT_CDIFF |
00003                    REPORT_NDIFF |
00004                    REPORT_ONLY_FIRST_FAILURE)

Definition at line 154 of file doctest.py.

Definition at line 139 of file doctest.py.

tuple doctest.TestResults = namedtuple('TestResults', 'failed attempted')

Definition at line 107 of file doctest.py.