Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Static Private Attributes
unittest.loader.TestLoader Class Reference
Inheritance diagram for unittest.loader.TestLoader:
Inheritance graph
[legend]
Collaboration diagram for unittest.loader.TestLoader:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def loadTestsFromTestCase
def loadTestsFromModule
def loadTestsFromName
def loadTestsFromNames
def getTestCaseNames
def discover

Public Attributes

_PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt
struct _typeobjectob_type

Static Public Attributes

string testMethodPrefix = 'test'
tuple sortTestMethodsUsing = staticmethod(util.three_way_cmp)
 suiteClass = suite.TestSuite

Private Member Functions

def _get_directory_containing_module
def _get_name_from_path
def _get_module_from_name
def _match_path
def _find_tests

Static Private Attributes

 _top_level_dir = None

Detailed Description

This class is responsible for loading tests according to various criteria
and returning them wrapped in a TestSuite

Definition at line 38 of file loader.py.


Member Function Documentation

def unittest.loader.TestLoader._find_tests (   self,
  start_dir,
  pattern 
) [private]
Used by discovery. Yields test suites it loads.

Definition at line 242 of file loader.py.

00242 
00243     def _find_tests(self, start_dir, pattern):
00244         """Used by discovery. Yields test suites it loads."""
00245         paths = os.listdir(start_dir)
00246 
00247         for path in paths:
00248             full_path = os.path.join(start_dir, path)
00249             if os.path.isfile(full_path):
00250                 if not VALID_MODULE_NAME.match(path):
00251                     # valid Python identifiers only
00252                     continue
00253                 if not self._match_path(path, full_path, pattern):
00254                     continue
00255                 # if the test file matches, load it
00256                 name = self._get_name_from_path(full_path)
00257                 try:
00258                     module = self._get_module_from_name(name)
00259                 except:
00260                     yield _make_failed_import_test(name, self.suiteClass)
00261                 else:
00262                     mod_file = os.path.abspath(getattr(module, '__file__', full_path))
00263                     realpath = os.path.splitext(mod_file)[0]
00264                     fullpath_noext = os.path.splitext(full_path)[0]
00265                     if realpath.lower() != fullpath_noext.lower():
00266                         module_dir = os.path.dirname(realpath)
00267                         mod_name = os.path.splitext(os.path.basename(full_path))[0]
00268                         expected_dir = os.path.dirname(full_path)
00269                         msg = ("%r module incorrectly imported from %r. Expected %r. "
00270                                "Is this module globally installed?")
00271                         raise ImportError(msg % (mod_name, module_dir, expected_dir))
00272                     yield self.loadTestsFromModule(module)
00273             elif os.path.isdir(full_path):
00274                 if not os.path.isfile(os.path.join(full_path, '__init__.py')):
00275                     continue
00276 
00277                 load_tests = None
00278                 tests = None
00279                 if fnmatch(path, pattern):
00280                     # only check load_tests if the package directory itself matches the filter
00281                     name = self._get_name_from_path(full_path)
00282                     package = self._get_module_from_name(name)
00283                     load_tests = getattr(package, 'load_tests', None)
00284                     tests = self.loadTestsFromModule(package, use_load_tests=False)
00285 
00286                 if load_tests is None:
00287                     if tests is not None:
00288                         # tests loaded from package file
00289                         yield tests
00290                     # recurse into the package
00291                     for test in self._find_tests(full_path, pattern):
00292                         yield test
00293                 else:
00294                     try:
00295                         yield load_tests(self, tests, pattern)
00296                     except Exception as e:
00297                         yield _make_failed_load_tests(package.__name__, e,
00298                                                       self.suiteClass)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.loader.TestLoader._get_directory_containing_module (   self,
  module_name 
) [private]

Definition at line 212 of file loader.py.

00212 
00213     def _get_directory_containing_module(self, module_name):
00214         module = sys.modules[module_name]
00215         full_path = os.path.abspath(module.__file__)
00216 
00217         if os.path.basename(full_path).lower().startswith('__init__.py'):
00218             return os.path.dirname(os.path.dirname(full_path))
00219         else:
00220             # here we have been given a module rather than a package - so
00221             # all we can do is search the *same* directory the module is in
00222             # should an exception be raised instead
00223             return os.path.dirname(full_path)

Here is the caller graph for this function:

def unittest.loader.TestLoader._get_module_from_name (   self,
  name 
) [private]

Definition at line 234 of file loader.py.

00234 
00235     def _get_module_from_name(self, name):
00236         __import__(name)
00237         return sys.modules[name]

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.loader.TestLoader._get_name_from_path (   self,
  path 
) [private]

Definition at line 224 of file loader.py.

00224 
00225     def _get_name_from_path(self, path):
00226         path = os.path.splitext(os.path.normpath(path))[0]
00227 
00228         _relpath = os.path.relpath(path, self._top_level_dir)
00229         assert not os.path.isabs(_relpath), "Path must be within the project"
00230         assert not _relpath.startswith('..'), "Path must be within the project"
00231 
00232         name = _relpath.replace(os.path.sep, '.')
00233         return name

Here is the caller graph for this function:

def unittest.loader.TestLoader._match_path (   self,
  path,
  full_path,
  pattern 
) [private]

Definition at line 238 of file loader.py.

00238 
00239     def _match_path(self, path, full_path, pattern):
00240         # override this method to use alternative matching strategy
00241         return fnmatch(path, pattern)

Here is the caller graph for this function:

def unittest.loader.TestLoader.discover (   self,
  start_dir,
  pattern = 'test*.py',
  top_level_dir = None 
)
Find and return all test modules from the specified start
directory, recursing into subdirectories to find them and return all
tests found within them. Only test files that match the pattern will
be loaded. (Using shell style pattern matching.)

All test modules must be importable from the top level of the project.
If the start directory is not the top level directory then the top
level directory must be specified separately.

If a test package name (directory with '__init__.py') matches the
pattern then the package will be checked for a 'load_tests' function. If
this exists then it will be called with loader, tests, pattern.

If load_tests exists then discovery does  *not* recurse into the package,
load_tests is responsible for loading all tests in the package.

The pattern is deliberately not stored as a loader attribute so that
packages can continue discovery themselves. top_level_dir is stored so
load_tests does not need to pass this argument in to loader.discover().

Definition at line 148 of file loader.py.

00148 
00149     def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
00150         """Find and return all test modules from the specified start
00151         directory, recursing into subdirectories to find them and return all
00152         tests found within them. Only test files that match the pattern will
00153         be loaded. (Using shell style pattern matching.)
00154 
00155         All test modules must be importable from the top level of the project.
00156         If the start directory is not the top level directory then the top
00157         level directory must be specified separately.
00158 
00159         If a test package name (directory with '__init__.py') matches the
00160         pattern then the package will be checked for a 'load_tests' function. If
00161         this exists then it will be called with loader, tests, pattern.
00162 
00163         If load_tests exists then discovery does  *not* recurse into the package,
00164         load_tests is responsible for loading all tests in the package.
00165 
00166         The pattern is deliberately not stored as a loader attribute so that
00167         packages can continue discovery themselves. top_level_dir is stored so
00168         load_tests does not need to pass this argument in to loader.discover().
00169         """
00170         set_implicit_top = False
00171         if top_level_dir is None and self._top_level_dir is not None:
00172             # make top_level_dir optional if called from load_tests in a package
00173             top_level_dir = self._top_level_dir
00174         elif top_level_dir is None:
00175             set_implicit_top = True
00176             top_level_dir = start_dir
00177 
00178         top_level_dir = os.path.abspath(top_level_dir)
00179 
00180         if not top_level_dir in sys.path:
00181             # all test modules must be importable from the top level directory
00182             # should we *unconditionally* put the start directory in first
00183             # in sys.path to minimise likelihood of conflicts between installed
00184             # modules and development versions?
00185             sys.path.insert(0, top_level_dir)
00186         self._top_level_dir = top_level_dir
00187 
00188         is_not_importable = False
00189         if os.path.isdir(os.path.abspath(start_dir)):
00190             start_dir = os.path.abspath(start_dir)
00191             if start_dir != top_level_dir:
00192                 is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py'))
00193         else:
00194             # support for discovery from dotted module names
00195             try:
00196                 __import__(start_dir)
00197             except ImportError:
00198                 is_not_importable = True
00199             else:
00200                 the_module = sys.modules[start_dir]
00201                 top_part = start_dir.split('.')[0]
00202                 start_dir = os.path.abspath(os.path.dirname((the_module.__file__)))
00203                 if set_implicit_top:
00204                     self._top_level_dir = self._get_directory_containing_module(top_part)
00205                     sys.path.remove(top_level_dir)
00206 
00207         if is_not_importable:
00208             raise ImportError('Start directory is not importable: %r' % start_dir)
00209 
00210         tests = list(self._find_tests(start_dir, pattern))
00211         return self.suiteClass(tests)

Here is the call graph for this function:

def unittest.loader.TestLoader.getTestCaseNames (   self,
  testCaseClass 
)
Return a sorted sequence of method names found within testCaseClass

Definition at line 135 of file loader.py.

00135 
00136     def getTestCaseNames(self, testCaseClass):
00137         """Return a sorted sequence of method names found within testCaseClass
00138         """
00139         def isTestMethod(attrname, testCaseClass=testCaseClass,
00140                          prefix=self.testMethodPrefix):
00141             return attrname.startswith(prefix) and \
00142                 hasattr(getattr(testCaseClass, attrname), '__call__')
00143         testFnNames = testFnNames = list(filter(isTestMethod,
00144                                                 dir(testCaseClass)))
00145         if self.sortTestMethodsUsing:
00146             testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
00147         return testFnNames

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.loader.TestLoader.loadTestsFromModule (   self,
  module,
  use_load_tests = True 
)
Return a suite of all tests cases contained in the given module

Definition at line 59 of file loader.py.

00059 
00060     def loadTestsFromModule(self, module, use_load_tests=True):
00061         """Return a suite of all tests cases contained in the given module"""
00062         tests = []
00063         for name in dir(module):
00064             obj = getattr(module, name)
00065             if isinstance(obj, type) and issubclass(obj, case.TestCase):
00066                 tests.append(self.loadTestsFromTestCase(obj))
00067 
00068         load_tests = getattr(module, 'load_tests', None)
00069         tests = self.suiteClass(tests)
00070         if use_load_tests and load_tests is not None:
00071             try:
00072                 return load_tests(self, tests, None)
00073             except Exception as e:
00074                 return _make_failed_load_tests(module.__name__, e,
00075                                                self.suiteClass)
00076         return tests

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.loader.TestLoader.loadTestsFromName (   self,
  name,
  module = None 
)
Return a suite of all tests cases given a string specifier.

The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.

The method optionally resolves the names relative to a given module.

Definition at line 77 of file loader.py.

00077 
00078     def loadTestsFromName(self, name, module=None):
00079         """Return a suite of all tests cases given a string specifier.
00080 
00081         The name may resolve either to a module, a test case class, a
00082         test method within a test case class, or a callable object which
00083         returns a TestCase or TestSuite instance.
00084 
00085         The method optionally resolves the names relative to a given module.
00086         """
00087         parts = name.split('.')
00088         if module is None:
00089             parts_copy = parts[:]
00090             while parts_copy:
00091                 try:
00092                     module = __import__('.'.join(parts_copy))
00093                     break
00094                 except ImportError:
00095                     del parts_copy[-1]
00096                     if not parts_copy:
00097                         raise
00098             parts = parts[1:]
00099         obj = module
00100         for part in parts:
00101             parent, obj = obj, getattr(obj, part)
00102 
00103         if isinstance(obj, types.ModuleType):
00104             return self.loadTestsFromModule(obj)
00105         elif isinstance(obj, type) and issubclass(obj, case.TestCase):
00106             return self.loadTestsFromTestCase(obj)
00107         elif (isinstance(obj, types.FunctionType) and
00108               isinstance(parent, type) and
00109               issubclass(parent, case.TestCase)):
00110             name = obj.__name__
00111             inst = parent(name)
00112             # static methods follow a different path
00113             if not isinstance(getattr(inst, name), types.FunctionType):
00114                 return self.suiteClass([inst])
00115         elif isinstance(obj, suite.TestSuite):
00116             return obj
00117         if hasattr(obj, '__call__'):
00118             test = obj()
00119             if isinstance(test, suite.TestSuite):
00120                 return test
00121             elif isinstance(test, case.TestCase):
00122                 return self.suiteClass([test])
00123             else:
00124                 raise TypeError("calling %s returned %s, not a test" %
00125                                 (obj, test))
00126         else:
00127             raise TypeError("don't know how to make test from: %s" % obj)

Here is the call graph for this function:

Here is the caller graph for this function:

def unittest.loader.TestLoader.loadTestsFromNames (   self,
  names,
  module = None 
)
Return a suite of all tests cases found using the given sequence
of string specifiers. See 'loadTestsFromName()'.

Definition at line 128 of file loader.py.

00128 
00129     def loadTestsFromNames(self, names, module=None):
00130         """Return a suite of all tests cases found using the given sequence
00131         of string specifiers. See 'loadTestsFromName()'.
00132         """
00133         suites = [self.loadTestsFromName(name, module) for name in names]
00134         return self.suiteClass(suites)

Here is the call graph for this function:

def unittest.loader.TestLoader.loadTestsFromTestCase (   self,
  testCaseClass 
)
Return a suite of all tests cases contained in testCaseClass

Definition at line 48 of file loader.py.

00048 
00049     def loadTestsFromTestCase(self, testCaseClass):
00050         """Return a suite of all tests cases contained in testCaseClass"""
00051         if issubclass(testCaseClass, suite.TestSuite):
00052             raise TypeError("Test cases should not be derived from TestSuite." \
00053                                 " Maybe you meant to derive from TestCase?")
00054         testCaseNames = self.getTestCaseNames(testCaseClass)
00055         if not testCaseNames and hasattr(testCaseClass, 'runTest'):
00056             testCaseNames = ['runTest']
00057         loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
00058         return loaded_suite

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Definition at line 46 of file loader.py.

Definition at line 107 of file object.h.

struct _typeobject* _object::ob_type [inherited]

Definition at line 108 of file object.h.

Definition at line 44 of file loader.py.

Definition at line 45 of file loader.py.

Definition at line 43 of file loader.py.


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