loader.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # Copyright (C) 2016 Intel Corporation
  2. # Released under the MIT license (see COPYING.MIT)
  3. import os
  4. import re
  5. import sys
  6. import unittest
  7. import inspect
  8. from oeqa.core.utils.path import findFile
  9. from oeqa.core.utils.test import getSuiteModules, getCaseID
  10. from oeqa.core.exception import OEQATestNotFound
  11. from oeqa.core.case import OETestCase
  12. from oeqa.core.decorator import decoratorClasses, OETestDecorator, \
  13. OETestFilter, OETestDiscover
  14. # When loading tests, the unittest framework stores any exceptions and
  15. # displays them only when the run method is called.
  16. #
  17. # For our purposes, it is better to raise the exceptions in the loading
  18. # step rather than waiting to run the test suite.
  19. #
  20. # Generate the function definition because this differ across python versions
  21. # Python >= 3.4.4 uses tree parameters instead four but for example Python 3.5.3
  22. # ueses four parameters so isn't incremental.
  23. _failed_test_args = inspect.getargspec(unittest.loader._make_failed_test).args
  24. exec("""def _make_failed_test(%s): raise exception""" % ', '.join(_failed_test_args))
  25. unittest.loader._make_failed_test = _make_failed_test
  26. def _find_duplicated_modules(suite, directory):
  27. for module in getSuiteModules(suite):
  28. path = findFile('%s.py' % module, directory)
  29. if path:
  30. raise ImportError("Duplicated %s module found in %s" % (module, path))
  31. def _built_modules_dict(modules):
  32. modules_dict = {}
  33. if modules == None:
  34. return modules_dict
  35. for module in modules:
  36. # Assumption: package and module names do not contain upper case
  37. # characters, whereas class names do
  38. m = re.match(r'^([^A-Z]+)(?:\.([A-Z][^.]*)(?:\.([^.]+))?)?$', module)
  39. module_name, class_name, test_name = m.groups()
  40. if module_name and module_name not in modules_dict:
  41. modules_dict[module_name] = {}
  42. if class_name and class_name not in modules_dict[module_name]:
  43. modules_dict[module_name][class_name] = []
  44. if test_name and test_name not in modules_dict[module_name][class_name]:
  45. modules_dict[module_name][class_name].append(test_name)
  46. return modules_dict
  47. class OETestLoader(unittest.TestLoader):
  48. caseClass = OETestCase
  49. kwargs_names = ['testMethodPrefix', 'sortTestMethodUsing', 'suiteClass',
  50. '_top_level_dir']
  51. def __init__(self, tc, module_paths, modules, tests, modules_required,
  52. filters, *args, **kwargs):
  53. self.tc = tc
  54. self.modules = _built_modules_dict(modules)
  55. self.tests = tests
  56. self.modules_required = modules_required
  57. self.filters = filters
  58. self.decorator_filters = [d for d in decoratorClasses if \
  59. issubclass(d, OETestFilter)]
  60. self._validateFilters(self.filters, self.decorator_filters)
  61. self.used_filters = [d for d in self.decorator_filters
  62. for f in self.filters
  63. if f in d.attrs]
  64. if isinstance(module_paths, str):
  65. module_paths = [module_paths]
  66. elif not isinstance(module_paths, list):
  67. raise TypeError('module_paths must be a str or a list of str')
  68. self.module_paths = module_paths
  69. for kwname in self.kwargs_names:
  70. if kwname in kwargs:
  71. setattr(self, kwname, kwargs[kwname])
  72. self._patchCaseClass(self.caseClass)
  73. super(OETestLoader, self).__init__()
  74. def _patchCaseClass(self, testCaseClass):
  75. # Adds custom attributes to the OETestCase class
  76. setattr(testCaseClass, 'tc', self.tc)
  77. setattr(testCaseClass, 'td', self.tc.td)
  78. setattr(testCaseClass, 'logger', self.tc.logger)
  79. def _validateFilters(self, filters, decorator_filters):
  80. # Validate if filter isn't empty
  81. for key,value in filters.items():
  82. if not value:
  83. raise TypeError("Filter %s specified is empty" % key)
  84. # Validate unique attributes
  85. attr_filters = [attr for clss in decorator_filters \
  86. for attr in clss.attrs]
  87. dup_attr = [attr for attr in attr_filters
  88. if attr_filters.count(attr) > 1]
  89. if dup_attr:
  90. raise TypeError('Detected duplicated attribute(s) %s in filter'
  91. ' decorators' % ' ,'.join(dup_attr))
  92. # Validate if filter is supported
  93. for f in filters:
  94. if f not in attr_filters:
  95. classes = ', '.join([d.__name__ for d in decorator_filters])
  96. raise TypeError('Found "%s" filter but not declared in any of '
  97. '%s decorators' % (f, classes))
  98. def _registerTestCase(self, case):
  99. case_id = case.id()
  100. self.tc._registry['cases'][case_id] = case
  101. def _handleTestCaseDecorators(self, case):
  102. def _handle(obj):
  103. if isinstance(obj, OETestDecorator):
  104. if not obj.__class__ in decoratorClasses:
  105. raise Exception("Decorator %s isn't registered" \
  106. " in decoratorClasses." % obj.__name__)
  107. obj.bind(self.tc._registry, case)
  108. def _walk_closure(obj):
  109. if hasattr(obj, '__closure__') and obj.__closure__:
  110. for f in obj.__closure__:
  111. obj = f.cell_contents
  112. _handle(obj)
  113. _walk_closure(obj)
  114. method = getattr(case, case._testMethodName, None)
  115. _walk_closure(method)
  116. def _filterTest(self, case):
  117. """
  118. Returns True if test case must be filtered, False otherwise.
  119. """
  120. # XXX; If the module has more than one namespace only use
  121. # the first to support run the whole module specifying the
  122. # <module_name>.[test_class].[test_name]
  123. module_name_small = case.__module__.split('.')[0]
  124. module_name = case.__module__
  125. class_name = case.__class__.__name__
  126. test_name = case._testMethodName
  127. if self.modules:
  128. module = None
  129. try:
  130. module = self.modules[module_name_small]
  131. except KeyError:
  132. try:
  133. module = self.modules[module_name]
  134. except KeyError:
  135. return True
  136. if module:
  137. if not class_name in module:
  138. return True
  139. if module[class_name]:
  140. if test_name not in module[class_name]:
  141. return True
  142. # Decorator filters
  143. if self.filters and isinstance(case, OETestCase):
  144. filters = self.filters.copy()
  145. case_decorators = [cd for cd in case.decorators
  146. if cd.__class__ in self.used_filters]
  147. # Iterate over case decorators to check if needs to be filtered.
  148. for cd in case_decorators:
  149. if cd.filtrate(filters):
  150. return True
  151. # Case is missing one or more decorators for all the filters
  152. # being used, so filter test case.
  153. if filters:
  154. return True
  155. return False
  156. def _getTestCase(self, testCaseClass, tcName):
  157. if not hasattr(testCaseClass, '__oeqa_loader') and \
  158. issubclass(testCaseClass, OETestCase):
  159. # In order to support data_vars validation
  160. # monkey patch the default setUp/tearDown{Class} to use
  161. # the ones provided by OETestCase
  162. setattr(testCaseClass, 'setUpClassMethod',
  163. getattr(testCaseClass, 'setUpClass'))
  164. setattr(testCaseClass, 'tearDownClassMethod',
  165. getattr(testCaseClass, 'tearDownClass'))
  166. setattr(testCaseClass, 'setUpClass',
  167. testCaseClass._oeSetUpClass)
  168. setattr(testCaseClass, 'tearDownClass',
  169. testCaseClass._oeTearDownClass)
  170. # In order to support decorators initialization
  171. # monkey patch the default setUp/tearDown to use
  172. # a setUpDecorators/tearDownDecorators that methods
  173. # will call setUp/tearDown original methods.
  174. setattr(testCaseClass, 'setUpMethod',
  175. getattr(testCaseClass, 'setUp'))
  176. setattr(testCaseClass, 'tearDownMethod',
  177. getattr(testCaseClass, 'tearDown'))
  178. setattr(testCaseClass, 'setUp', testCaseClass._oeSetUp)
  179. setattr(testCaseClass, 'tearDown', testCaseClass._oeTearDown)
  180. setattr(testCaseClass, '__oeqa_loader', True)
  181. case = testCaseClass(tcName)
  182. if isinstance(case, OETestCase):
  183. setattr(case, 'decorators', [])
  184. return case
  185. def loadTestsFromTestCase(self, testCaseClass):
  186. """
  187. Returns a suite of all tests cases contained in testCaseClass.
  188. """
  189. if issubclass(testCaseClass, unittest.suite.TestSuite):
  190. raise TypeError("Test cases should not be derived from TestSuite." \
  191. " Maybe you meant to derive %s from TestCase?" \
  192. % testCaseClass.__name__)
  193. if not issubclass(testCaseClass, unittest.case.TestCase):
  194. raise TypeError("Test %s is not derived from %s" % \
  195. (testCaseClass.__name__, unittest.case.TestCase.__name__))
  196. testCaseNames = self.getTestCaseNames(testCaseClass)
  197. if not testCaseNames and hasattr(testCaseClass, 'runTest'):
  198. testCaseNames = ['runTest']
  199. suite = []
  200. for tcName in testCaseNames:
  201. case = self._getTestCase(testCaseClass, tcName)
  202. # Filer by case id
  203. if not (self.tests and not 'all' in self.tests
  204. and not getCaseID(case) in self.tests):
  205. self._handleTestCaseDecorators(case)
  206. # Filter by decorators
  207. if not self._filterTest(case):
  208. self._registerTestCase(case)
  209. suite.append(case)
  210. return self.suiteClass(suite)
  211. def _required_modules_validation(self):
  212. """
  213. Search in Test context registry if a required
  214. test is found, raise an exception when not found.
  215. """
  216. for module in self.modules_required:
  217. found = False
  218. # The module name is splitted to only compare the
  219. # first part of a test case id.
  220. comp_len = len(module.split('.'))
  221. for case in self.tc._registry['cases']:
  222. case_comp = '.'.join(case.split('.')[0:comp_len])
  223. if module == case_comp:
  224. found = True
  225. break
  226. if not found:
  227. raise OEQATestNotFound("Not found %s in loaded test cases" % \
  228. module)
  229. def discover(self):
  230. big_suite = self.suiteClass()
  231. for path in self.module_paths:
  232. _find_duplicated_modules(big_suite, path)
  233. suite = super(OETestLoader, self).discover(path,
  234. pattern='*.py', top_level_dir=path)
  235. big_suite.addTests(suite)
  236. cases = None
  237. discover_classes = [clss for clss in decoratorClasses
  238. if issubclass(clss, OETestDiscover)]
  239. for clss in discover_classes:
  240. cases = clss.discover(self.tc._registry)
  241. if self.modules_required:
  242. self._required_modules_validation()
  243. return self.suiteClass(cases) if cases else big_suite
  244. def _filterModule(self, module):
  245. if module.__name__ in sys.builtin_module_names:
  246. msg = 'Tried to import %s test module but is a built-in'
  247. raise ImportError(msg % module.__name__)
  248. # XXX; If the module has more than one namespace only use
  249. # the first to support run the whole module specifying the
  250. # <module_name>.[test_class].[test_name]
  251. module_name_small = module.__name__.split('.')[0]
  252. module_name = module.__name__
  253. # Normal test modules are loaded if no modules were specified,
  254. # if module is in the specified module list or if 'all' is in
  255. # module list.
  256. # Underscore modules are loaded only if specified in module list.
  257. load_module = True if not module_name.startswith('_') \
  258. and (not self.modules \
  259. or module_name in self.modules \
  260. or module_name_small in self.modules \
  261. or 'all' in self.modules) \
  262. else False
  263. load_underscore = True if module_name.startswith('_') \
  264. and (module_name in self.modules or \
  265. module_name_small in self.modules) \
  266. else False
  267. return (load_module, load_underscore)
  268. # XXX After Python 3.5, remove backward compatibility hacks for
  269. # use_load_tests deprecation via *args and **kws. See issue 16662.
  270. if sys.version_info >= (3,5):
  271. def loadTestsFromModule(self, module, *args, pattern=None, **kws):
  272. """
  273. Returns a suite of all tests cases contained in module.
  274. """
  275. load_module, load_underscore = self._filterModule(module)
  276. if load_module or load_underscore:
  277. return super(OETestLoader, self).loadTestsFromModule(
  278. module, *args, pattern=pattern, **kws)
  279. else:
  280. return self.suiteClass()
  281. else:
  282. def loadTestsFromModule(self, module, use_load_tests=True):
  283. """
  284. Returns a suite of all tests cases contained in module.
  285. """
  286. load_module, load_underscore = self._filterModule(module)
  287. if load_module or load_underscore:
  288. return super(OETestLoader, self).loadTestsFromModule(
  289. module, use_load_tests)
  290. else:
  291. return self.suiteClass()