home *** CD-ROM | disk | FTP | other *** search
/ Freelog 116 / FreelogNo116-JuilletSeptembre2013.iso / Bureautique / gImageReader / gimagereader_0.9-1_win32.exe / bin / unittest / loader.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2011-03-24  |  11KB  |  314 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.7)
  3.  
  4. '''Loading unittests.'''
  5. import os
  6. import re
  7. import sys
  8. import traceback
  9. import types
  10. from functools import cmp_to_key as _CmpToKey
  11. from fnmatch import fnmatch
  12. from  import case, suite
  13. __unittest = True
  14. VALID_MODULE_NAME = re.compile('[_a-z]\\w*\\.py$', re.IGNORECASE)
  15.  
  16. def _make_failed_import_test(name, suiteClass):
  17.     message = 'Failed to import test module: %s\n%s' % (name, traceback.format_exc())
  18.     return _make_failed_test('ModuleImportFailure', name, ImportError(message), suiteClass)
  19.  
  20.  
  21. def _make_failed_load_tests(name, exception, suiteClass):
  22.     return _make_failed_test('LoadTestsFailure', name, exception, suiteClass)
  23.  
  24.  
  25. def _make_failed_test(classname, methodname, exception, suiteClass):
  26.     
  27.     def testFailure(self):
  28.         raise exception
  29.  
  30.     attrs = {
  31.         methodname: testFailure }
  32.     TestClass = type(classname, (case.TestCase,), attrs)
  33.     return suiteClass((TestClass(methodname),))
  34.  
  35.  
  36. class TestLoader(object):
  37.     '''
  38.     This class is responsible for loading tests according to various criteria
  39.     and returning them wrapped in a TestSuite
  40.     '''
  41.     testMethodPrefix = 'test'
  42.     sortTestMethodsUsing = cmp
  43.     suiteClass = suite.TestSuite
  44.     _top_level_dir = None
  45.     
  46.     def loadTestsFromTestCase(self, testCaseClass):
  47.         '''Return a suite of all tests cases contained in testCaseClass'''
  48.         if issubclass(testCaseClass, suite.TestSuite):
  49.             raise TypeError('Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?')
  50.         testCaseNames = self.getTestCaseNames(testCaseClass)
  51.         if not testCaseNames and hasattr(testCaseClass, 'runTest'):
  52.             testCaseNames = [
  53.                 'runTest']
  54.         loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
  55.         return loaded_suite
  56.  
  57.     
  58.     def loadTestsFromModule(self, module, use_load_tests = True):
  59.         '''Return a suite of all tests cases contained in the given module'''
  60.         tests = []
  61.         for name in dir(module):
  62.             obj = getattr(module, name)
  63.             if isinstance(obj, type) and issubclass(obj, case.TestCase):
  64.                 tests.append(self.loadTestsFromTestCase(obj))
  65.                 continue
  66.         load_tests = getattr(module, 'load_tests', None)
  67.         tests = self.suiteClass(tests)
  68.         if use_load_tests and load_tests is not None:
  69.             
  70.             try:
  71.                 return load_tests(self, tests, None)
  72.             except Exception:
  73.                 e = None
  74.                 return _make_failed_load_tests(module.__name__, e, self.suiteClass)
  75.             
  76.  
  77.         return tests
  78.  
  79.     
  80.     def loadTestsFromName(self, name, module = None):
  81.         '''Return a suite of all tests cases given a string specifier.
  82.  
  83.         The name may resolve either to a module, a test case class, a
  84.         test method within a test case class, or a callable object which
  85.         returns a TestCase or TestSuite instance.
  86.  
  87.         The method optionally resolves the names relative to a given module.
  88.         '''
  89.         parts = name.split('.')
  90.         if module is None:
  91.             parts_copy = parts[:]
  92.             while parts_copy:
  93.                 
  94.                 try:
  95.                     module = __import__('.'.join(parts_copy))
  96.                 continue
  97.                 except ImportError:
  98.                     del parts_copy[-1]
  99.                     if not parts_copy:
  100.                         raise 
  101.                     continue
  102.                 
  103.  
  104.             parts = parts[1:]
  105.         obj = module
  106.         for part in parts:
  107.             parent = obj
  108.             obj = getattr(obj, part)
  109.         
  110.         if isinstance(obj, types.ModuleType):
  111.             return self.loadTestsFromModule(obj)
  112.         if None(obj, type) and issubclass(obj, case.TestCase):
  113.             return self.loadTestsFromTestCase(obj)
  114.         if None(obj, types.UnboundMethodType) and isinstance(parent, type) and issubclass(parent, case.TestCase):
  115.             return self.suiteClass([
  116.                 parent(obj.__name__)])
  117.         if None(obj, suite.TestSuite):
  118.             return obj
  119.         if None(obj, '__call__'):
  120.             test = obj()
  121.             if isinstance(test, suite.TestSuite):
  122.                 return test
  123.             if None(test, case.TestCase):
  124.                 return self.suiteClass([
  125.                     test])
  126.             raise None('calling %s returned %s, not a test' % (obj, test))
  127.         raise TypeError("don't know how to make test from: %s" % obj)
  128.  
  129.     
  130.     def loadTestsFromNames(self, names, module = None):
  131.         """Return a suite of all tests cases found using the given sequence
  132.         of string specifiers. See 'loadTestsFromName()'.
  133.         """
  134.         suites = [ self.loadTestsFromName(name, module) for name in names ]
  135.         return self.suiteClass(suites)
  136.  
  137.     
  138.     def getTestCaseNames(self, testCaseClass):
  139.         '''Return a sorted sequence of method names found within testCaseClass
  140.         '''
  141.         
  142.         def isTestMethod(attrname, testCaseClass = testCaseClass, prefix = self.testMethodPrefix):
  143.             if attrname.startswith(prefix):
  144.                 pass
  145.             return hasattr(getattr(testCaseClass, attrname), '__call__')
  146.  
  147.         testFnNames = filter(isTestMethod, dir(testCaseClass))
  148.         if self.sortTestMethodsUsing:
  149.             testFnNames.sort(key = _CmpToKey(self.sortTestMethodsUsing))
  150.         return testFnNames
  151.  
  152.     
  153.     def discover(self, start_dir, pattern = 'test*.py', top_level_dir = None):
  154.         """Find and return all test modules from the specified start
  155.         directory, recursing into subdirectories to find them. Only test files
  156.         that match the pattern will be loaded. (Using shell style pattern
  157.         matching.)
  158.  
  159.         All test modules must be importable from the top level of the project.
  160.         If the start directory is not the top level directory then the top
  161.         level directory must be specified separately.
  162.  
  163.         If a test package name (directory with '__init__.py') matches the
  164.         pattern then the package will be checked for a 'load_tests' function. If
  165.         this exists then it will be called with loader, tests, pattern.
  166.  
  167.         If load_tests exists then discovery does  *not* recurse into the package,
  168.         load_tests is responsible for loading all tests in the package.
  169.  
  170.         The pattern is deliberately not stored as a loader attribute so that
  171.         packages can continue discovery themselves. top_level_dir is stored so
  172.         load_tests does not need to pass this argument in to loader.discover().
  173.         """
  174.         set_implicit_top = False
  175.         if top_level_dir is None and self._top_level_dir is not None:
  176.             top_level_dir = self._top_level_dir
  177.         elif top_level_dir is None:
  178.             set_implicit_top = True
  179.             top_level_dir = start_dir
  180.         top_level_dir = os.path.abspath(top_level_dir)
  181.         if top_level_dir not in sys.path:
  182.             sys.path.insert(0, top_level_dir)
  183.         self._top_level_dir = top_level_dir
  184.         is_not_importable = False
  185.         if os.path.isdir(os.path.abspath(start_dir)):
  186.             start_dir = os.path.abspath(start_dir)
  187.             if start_dir != top_level_dir:
  188.                 is_not_importable = not os.path.isfile(os.path.join(start_dir, '__init__.py'))
  189.             
  190.         else:
  191.             
  192.             try:
  193.                 __import__(start_dir)
  194.             except ImportError:
  195.                 is_not_importable = True
  196.  
  197.             the_module = sys.modules[start_dir]
  198.             top_part = start_dir.split('.')[0]
  199.             start_dir = os.path.abspath(os.path.dirname(the_module.__file__))
  200.             if set_implicit_top:
  201.                 self._top_level_dir = self._get_directory_containing_module(top_part)
  202.                 sys.path.remove(top_level_dir)
  203.         if is_not_importable:
  204.             raise ImportError('Start directory is not importable: %r' % start_dir)
  205.         tests = list(self._find_tests(start_dir, pattern))
  206.         return self.suiteClass(tests)
  207.  
  208.     
  209.     def _get_directory_containing_module(self, module_name):
  210.         module = sys.modules[module_name]
  211.         full_path = os.path.abspath(module.__file__)
  212.         if os.path.basename(full_path).lower().startswith('__init__.py'):
  213.             return os.path.dirname(os.path.dirname(full_path))
  214.         return None.path.dirname(full_path)
  215.  
  216.     
  217.     def _get_name_from_path(self, path):
  218.         path = os.path.splitext(os.path.normpath(path))[0]
  219.         _relpath = os.path.relpath(path, self._top_level_dir)
  220.         if not not os.path.isabs(_relpath):
  221.             raise AssertionError, 'Path must be within the project'
  222.         if not not None.startswith('..'):
  223.             raise AssertionError, 'Path must be within the project'
  224.         name = None.replace(os.path.sep, '.')
  225.         return name
  226.  
  227.     
  228.     def _get_module_from_name(self, name):
  229.         __import__(name)
  230.         return sys.modules[name]
  231.  
  232.     
  233.     def _match_path(self, path, full_path, pattern):
  234.         return fnmatch(path, pattern)
  235.  
  236.     
  237.     def _find_tests(self, start_dir, pattern):
  238.         '''Used by discovery. Yields test suites it loads.'''
  239.         paths = os.listdir(start_dir)
  240.         for path in paths:
  241.             full_path = os.path.join(start_dir, path)
  242.             if os.path.isfile(full_path):
  243.                 if not VALID_MODULE_NAME.match(path):
  244.                     continue
  245.                 if not self._match_path(path, full_path, pattern):
  246.                     continue
  247.                 name = self._get_name_from_path(full_path)
  248.                 
  249.                 try:
  250.                     module = self._get_module_from_name(name)
  251.                 except:
  252.                     yield _make_failed_import_test(name, self.suiteClass)
  253.  
  254.                 mod_file = os.path.abspath(getattr(module, '__file__', full_path))
  255.                 realpath = os.path.splitext(mod_file)[0]
  256.                 fullpath_noext = os.path.splitext(full_path)[0]
  257.                 if realpath.lower() != fullpath_noext.lower():
  258.                     module_dir = os.path.dirname(realpath)
  259.                     mod_name = os.path.splitext(os.path.basename(full_path))[0]
  260.                     expected_dir = os.path.dirname(full_path)
  261.                     msg = '%r module incorrectly imported from %r. Expected %r. Is this module globally installed?'
  262.                     raise ImportError(msg % (mod_name, module_dir, expected_dir))
  263.                 yield self.loadTestsFromModule(module)
  264.                 continue
  265.             if not os.path.isdir(full_path) or os.path.isfile(os.path.join(full_path, '__init__.py')):
  266.                 continue
  267.             load_tests = None
  268.             tests = None
  269.             if fnmatch(path, pattern):
  270.                 name = self._get_name_from_path(full_path)
  271.                 package = self._get_module_from_name(name)
  272.                 load_tests = getattr(package, 'load_tests', None)
  273.                 tests = self.loadTestsFromModule(package, use_load_tests = False)
  274.             if load_tests is None:
  275.                 if tests is not None:
  276.                     yield tests
  277.                 for test in self._find_tests(full_path, pattern):
  278.                     yield test
  279.                 
  280.             else:
  281.                 
  282.                 try:
  283.                     yield load_tests(self, tests, pattern)
  284.                 except Exception:
  285.                     e = None
  286.                     yield _make_failed_load_tests(package.__name__, e, self.suiteClass)
  287.                 
  288.  
  289.         
  290.  
  291.  
  292. defaultTestLoader = TestLoader()
  293.  
  294. def _makeLoader(prefix, sortUsing, suiteClass = None):
  295.     loader = TestLoader()
  296.     loader.sortTestMethodsUsing = sortUsing
  297.     loader.testMethodPrefix = prefix
  298.     if suiteClass:
  299.         loader.suiteClass = suiteClass
  300.     return loader
  301.  
  302.  
  303. def getTestCaseNames(testCaseClass, prefix, sortUsing = cmp):
  304.     return _makeLoader(prefix, sortUsing).getTestCaseNames(testCaseClass)
  305.  
  306.  
  307. def makeSuite(testCaseClass, prefix = 'test', sortUsing = cmp, suiteClass = suite.TestSuite):
  308.     return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromTestCase(testCaseClass)
  309.  
  310.  
  311. def findTestCases(module, prefix = 'test', sortUsing = cmp, suiteClass = suite.TestSuite):
  312.     return _makeLoader(prefix, sortUsing, suiteClass).loadTestsFromModule(module)
  313.  
  314.