PageRenderTime 44ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/unittest/loader.py

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