Back to index

python3.2  3.2.2
Public Member Functions | Private Member Functions | Private Attributes
doctest.DocTestFinder Class Reference

List of all members.

Public Member Functions

def __init__
def find

Private Member Functions

def _from_module
def _find
def _get_test
def _find_lineno

Private Attributes

 _parser
 _verbose
 _recurse
 _exclude_empty

Detailed Description

  1. DocTest Finder
    A class used to extract the DocTests that are relevant to a given
    object, from its docstring and the docstrings of its contained
    objects.  Doctests can currently be extracted from the following
    object types: modules, functions, classes, methods, staticmethods,
    classmethods, and properties.
    

Definition at line 739 of file doctest.py.


Constructor & Destructor Documentation

def doctest.DocTestFinder.__init__ (   self,
  verbose = False,
  parser = DocTestParser(),
  recurse = True,
  exclude_empty = True 
)
Create a new doctest finder.

The optional argument `parser` specifies a class or
function that should be used to create new DocTest objects (or
objects that implement the same interface as DocTest).  The
signature for this factory function should match the signature
of the DocTest constructor.

If the optional argument `recurse` is false, then `find` will
only examine the given object, and not any contained objects.

If the optional argument `exclude_empty` is false, then `find`
will include tests for objects with empty docstrings.

Definition at line 749 of file doctest.py.

00749 
00750                  recurse=True, exclude_empty=True):
00751         """
00752         Create a new doctest finder.
00753 
00754         The optional argument `parser` specifies a class or
00755         function that should be used to create new DocTest objects (or
00756         objects that implement the same interface as DocTest).  The
00757         signature for this factory function should match the signature
00758         of the DocTest constructor.
00759 
00760         If the optional argument `recurse` is false, then `find` will
00761         only examine the given object, and not any contained objects.
00762 
00763         If the optional argument `exclude_empty` is false, then `find`
00764         will include tests for objects with empty docstrings.
00765         """
00766         self._parser = parser
00767         self._verbose = verbose
00768         self._recurse = recurse
00769         self._exclude_empty = exclude_empty

Here is the caller graph for this function:


Member Function Documentation

def doctest.DocTestFinder._find (   self,
  tests,
  obj,
  name,
  module,
  source_lines,
  globs,
  seen 
) [private]
Find tests for the given object and any contained objects, and
add them to `tests`.

Definition at line 892 of file doctest.py.

00892 
00893     def _find(self, tests, obj, name, module, source_lines, globs, seen):
00894         """
00895         Find tests for the given object and any contained objects, and
00896         add them to `tests`.
00897         """
00898         if self._verbose:
00899             print('Finding tests in %s' % name)
00900 
00901         # If we've already processed this object, then ignore it.
00902         if id(obj) in seen:
00903             return
00904         seen[id(obj)] = 1
00905 
00906         # Find a test for this object, and add it to the list of tests.
00907         test = self._get_test(obj, name, module, globs, source_lines)
00908         if test is not None:
00909             tests.append(test)
00910 
00911         # Look for tests in a module's contained objects.
00912         if inspect.ismodule(obj) and self._recurse:
00913             for valname, val in obj.__dict__.items():
00914                 valname = '%s.%s' % (name, valname)
00915                 # Recurse to functions & classes.
00916                 if ((inspect.isfunction(val) or inspect.isclass(val)) and
00917                     self._from_module(module, val)):
00918                     self._find(tests, val, valname, module, source_lines,
00919                                globs, seen)
00920 
00921         # Look for tests in a module's __test__ dictionary.
00922         if inspect.ismodule(obj) and self._recurse:
00923             for valname, val in getattr(obj, '__test__', {}).items():
00924                 if not isinstance(valname, str):
00925                     raise ValueError("DocTestFinder.find: __test__ keys "
00926                                      "must be strings: %r" %
00927                                      (type(valname),))
00928                 if not (inspect.isfunction(val) or inspect.isclass(val) or
00929                         inspect.ismethod(val) or inspect.ismodule(val) or
00930                         isinstance(val, str)):
00931                     raise ValueError("DocTestFinder.find: __test__ values "
00932                                      "must be strings, functions, methods, "
00933                                      "classes, or modules: %r" %
00934                                      (type(val),))
00935                 valname = '%s.__test__.%s' % (name, valname)
00936                 self._find(tests, val, valname, module, source_lines,
00937                            globs, seen)
00938 
00939         # Look for tests in a class's contained objects.
00940         if inspect.isclass(obj) and self._recurse:
00941             for valname, val in obj.__dict__.items():
00942                 # Special handling for staticmethod/classmethod.
00943                 if isinstance(val, staticmethod):
00944                     val = getattr(obj, valname)
00945                 if isinstance(val, classmethod):
00946                     val = getattr(obj, valname).__func__
00947 
00948                 # Recurse to methods, properties, and nested classes.
00949                 if ((inspect.isfunction(val) or inspect.isclass(val) or
00950                       isinstance(val, property)) and
00951                       self._from_module(module, val)):
00952                     valname = '%s.%s' % (name, valname)
00953                     self._find(tests, val, valname, module, source_lines,
00954                                globs, seen)

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest.DocTestFinder._find_lineno (   self,
  obj,
  source_lines 
) [private]
Return a line number of the given object's docstring.  Note:
this method assumes that the object has a docstring.

Definition at line 992 of file doctest.py.

00992 
00993     def _find_lineno(self, obj, source_lines):
00994         """
00995         Return a line number of the given object's docstring.  Note:
00996         this method assumes that the object has a docstring.
00997         """
00998         lineno = None
00999 
01000         # Find the line number for modules.
01001         if inspect.ismodule(obj):
01002             lineno = 0
01003 
01004         # Find the line number for classes.
01005         # Note: this could be fooled if a class is defined multiple
01006         # times in a single file.
01007         if inspect.isclass(obj):
01008             if source_lines is None:
01009                 return None
01010             pat = re.compile(r'^\s*class\s*%s\b' %
01011                              getattr(obj, '__name__', '-'))
01012             for i, line in enumerate(source_lines):
01013                 if pat.match(line):
01014                     lineno = i
01015                     break
01016 
01017         # Find the line number for functions & methods.
01018         if inspect.ismethod(obj): obj = obj.__func__
01019         if inspect.isfunction(obj): obj = obj.__code__
01020         if inspect.istraceback(obj): obj = obj.tb_frame
01021         if inspect.isframe(obj): obj = obj.f_code
01022         if inspect.iscode(obj):
01023             lineno = getattr(obj, 'co_firstlineno', None)-1
01024 
01025         # Find the line number where the docstring starts.  Assume
01026         # that it's the first line that begins with a quote mark.
01027         # Note: this could be fooled by a multiline function
01028         # signature, where a continuation line begins with a quote
01029         # mark.
01030         if lineno is not None:
01031             if source_lines is None:
01032                 return lineno+1
01033             pat = re.compile('(^|.*:)\s*\w*("|\')')
01034             for lineno in range(lineno, len(source_lines)):
01035                 if pat.match(source_lines[lineno]):
01036                     return lineno
01037 
01038         # We couldn't find the line number.
01039         return None

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest.DocTestFinder._from_module (   self,
  module,
  object 
) [private]
Return true if the given object is defined in the given
module.

Definition at line 872 of file doctest.py.

00872 
00873     def _from_module(self, module, object):
00874         """
00875         Return true if the given object is defined in the given
00876         module.
00877         """
00878         if module is None:
00879             return True
00880         elif inspect.getmodule(object) is not None:
00881             return module is inspect.getmodule(object)
00882         elif inspect.isfunction(object):
00883             return module.__dict__ is object.__globals__
00884         elif inspect.isclass(object):
00885             return module.__name__ == object.__module__
00886         elif hasattr(object, '__module__'):
00887             return module.__name__ == object.__module__
00888         elif isinstance(object, property):
00889             return True # [XX] no way not be sure.
00890         else:
00891             raise ValueError("object must be a class or function")

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest.DocTestFinder._get_test (   self,
  obj,
  name,
  module,
  globs,
  source_lines 
) [private]
Return a DocTest for the given object, if it defines a docstring;
otherwise, return None.

Definition at line 955 of file doctest.py.

00955 
00956     def _get_test(self, obj, name, module, globs, source_lines):
00957         """
00958         Return a DocTest for the given object, if it defines a docstring;
00959         otherwise, return None.
00960         """
00961         # Extract the object's docstring.  If it doesn't have one,
00962         # then return None (no test for this object).
00963         if isinstance(obj, str):
00964             docstring = obj
00965         else:
00966             try:
00967                 if obj.__doc__ is None:
00968                     docstring = ''
00969                 else:
00970                     docstring = obj.__doc__
00971                     if not isinstance(docstring, str):
00972                         docstring = str(docstring)
00973             except (TypeError, AttributeError):
00974                 docstring = ''
00975 
00976         # Find the docstring's location in the file.
00977         lineno = self._find_lineno(obj, source_lines)
00978 
00979         # Don't bother if the docstring is empty.
00980         if self._exclude_empty and not docstring:
00981             return None
00982 
00983         # Return a DocTest for this object.
00984         if module is None:
00985             filename = None
00986         else:
00987             filename = getattr(module, '__file__', module.__name__)
00988             if filename[-4:] in (".pyc", ".pyo"):
00989                 filename = filename[:-1]
00990         return self._parser.get_doctest(docstring, globs, name,
00991                                         filename, lineno)

Here is the call graph for this function:

Here is the caller graph for this function:

def doctest.DocTestFinder.find (   self,
  obj,
  name = None,
  module = None,
  globs = None,
  extraglobs = None 
)
Return a list of the DocTests that are defined by the given
object's docstring, or by any of its contained objects'
docstrings.

The optional parameter `module` is the module that contains
the given object.  If the module is not specified or is None, then
the test finder will attempt to automatically determine the
correct module.  The object's module is used:

    - As a default namespace, if `globs` is not specified.
    - To prevent the DocTestFinder from extracting DocTests
      from objects that are imported from other modules.
    - To find the name of the file containing the object.
    - To help find the line number of the object within its
      file.

Contained objects whose module does not match `module` are ignored.

If `module` is False, no attempt to find the module will be made.
This is obscure, of use mostly in tests:  if `module` is False, or
is None but cannot be found automatically, then all objects are
considered to belong to the (non-existent) module, so all contained
objects will (recursively) be searched for doctests.

The globals for each DocTest is formed by combining `globs`
and `extraglobs` (bindings in `extraglobs` override bindings
in `globs`).  A new copy of the globals dictionary is created
for each DocTest.  If `globs` is not specified, then it
defaults to the module's `__dict__`, if specified, or {}
otherwise.  If `extraglobs` is not specified, then it defaults
to {}.

Definition at line 770 of file doctest.py.

00770 
00771     def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
00772         """
00773         Return a list of the DocTests that are defined by the given
00774         object's docstring, or by any of its contained objects'
00775         docstrings.
00776 
00777         The optional parameter `module` is the module that contains
00778         the given object.  If the module is not specified or is None, then
00779         the test finder will attempt to automatically determine the
00780         correct module.  The object's module is used:
00781 
00782             - As a default namespace, if `globs` is not specified.
00783             - To prevent the DocTestFinder from extracting DocTests
00784               from objects that are imported from other modules.
00785             - To find the name of the file containing the object.
00786             - To help find the line number of the object within its
00787               file.
00788 
00789         Contained objects whose module does not match `module` are ignored.
00790 
00791         If `module` is False, no attempt to find the module will be made.
00792         This is obscure, of use mostly in tests:  if `module` is False, or
00793         is None but cannot be found automatically, then all objects are
00794         considered to belong to the (non-existent) module, so all contained
00795         objects will (recursively) be searched for doctests.
00796 
00797         The globals for each DocTest is formed by combining `globs`
00798         and `extraglobs` (bindings in `extraglobs` override bindings
00799         in `globs`).  A new copy of the globals dictionary is created
00800         for each DocTest.  If `globs` is not specified, then it
00801         defaults to the module's `__dict__`, if specified, or {}
00802         otherwise.  If `extraglobs` is not specified, then it defaults
00803         to {}.
00804 
00805         """
00806         # If name was not specified, then extract it from the object.
00807         if name is None:
00808             name = getattr(obj, '__name__', None)
00809             if name is None:
00810                 raise ValueError("DocTestFinder.find: name must be given "
00811                         "when obj.__name__ doesn't exist: %r" %
00812                                  (type(obj),))
00813 
00814         # Find the module that contains the given object (if obj is
00815         # a module, then module=obj.).  Note: this may fail, in which
00816         # case module will be None.
00817         if module is False:
00818             module = None
00819         elif module is None:
00820             module = inspect.getmodule(obj)
00821 
00822         # Read the module's source code.  This is used by
00823         # DocTestFinder._find_lineno to find the line number for a
00824         # given object's docstring.
00825         try:
00826             file = inspect.getsourcefile(obj)
00827         except TypeError:
00828             source_lines = None
00829         else:
00830             if not file:
00831                 # Check to see if it's one of our special internal "files"
00832                 # (see __patched_linecache_getlines).
00833                 file = inspect.getfile(obj)
00834                 if not file[0]+file[-2:] == '<]>': file = None
00835             if file is None:
00836                 source_lines = None
00837             else:
00838                 if module is not None:
00839                     # Supply the module globals in case the module was
00840                     # originally loaded via a PEP 302 loader and
00841                     # file is not a valid filesystem path
00842                     source_lines = linecache.getlines(file, module.__dict__)
00843                 else:
00844                     # No access to a loader, so assume it's a normal
00845                     # filesystem path
00846                     source_lines = linecache.getlines(file)
00847                 if not source_lines:
00848                     source_lines = None
00849 
00850         # Initialize globals, and merge in extraglobs.
00851         if globs is None:
00852             if module is None:
00853                 globs = {}
00854             else:
00855                 globs = module.__dict__.copy()
00856         else:
00857             globs = globs.copy()
00858         if extraglobs is not None:
00859             globs.update(extraglobs)
00860         if '__name__' not in globs:
00861             globs['__name__'] = '__main__'  # provide a default module name
00862 
00863         # Recursively expore `obj`, extracting DocTests.
00864         tests = []
00865         self._find(tests, obj, name, module, source_lines, globs, {})
00866         # Sort the tests by alpha order of names, for consistency in
00867         # verbose-mode output.  This was a feature of doctest in Pythons
00868         # <= 2.3 that got lost by accident in 2.4.  It was repaired in
00869         # 2.4.4 and 2.5.
00870         tests.sort()
00871         return tests

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Definition at line 768 of file doctest.py.

Definition at line 765 of file doctest.py.

Definition at line 767 of file doctest.py.

Definition at line 766 of file doctest.py.


The documentation for this class was generated from the following file: