context.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. # Copyright (C) 2017 Intel Corporation
  2. # Released under the MIT license (see COPYING.MIT)
  3. import os
  4. import time
  5. import glob
  6. import sys
  7. import importlib
  8. import signal
  9. from shutil import copyfile
  10. from random import choice
  11. import oeqa
  12. import oe
  13. from oeqa.core.context import OETestContext, OETestContextExecutor
  14. from oeqa.core.exception import OEQAPreRun, OEQATestNotFound
  15. from oeqa.utils.commands import runCmd, get_bb_vars, get_test_layer
  16. class OESelftestTestContext(OETestContext):
  17. def __init__(self, td=None, logger=None, machines=None, config_paths=None):
  18. super(OESelftestTestContext, self).__init__(td, logger)
  19. self.machines = machines
  20. self.custommachine = None
  21. self.config_paths = config_paths
  22. def runTests(self, processes=None, machine=None, skips=[]):
  23. if machine:
  24. self.custommachine = machine
  25. if machine == 'random':
  26. self.custommachine = choice(self.machines)
  27. self.logger.info('Run tests with custom MACHINE set to: %s' % \
  28. self.custommachine)
  29. return super(OESelftestTestContext, self).runTests(processes, skips)
  30. def listTests(self, display_type, machine=None):
  31. return super(OESelftestTestContext, self).listTests(display_type)
  32. class OESelftestTestContextExecutor(OETestContextExecutor):
  33. _context_class = OESelftestTestContext
  34. _script_executor = 'oe-selftest'
  35. name = 'oe-selftest'
  36. help = 'oe-selftest test component'
  37. description = 'Executes selftest tests'
  38. def register_commands(self, logger, parser):
  39. group = parser.add_mutually_exclusive_group(required=True)
  40. group.add_argument('-a', '--run-all-tests', default=False,
  41. action="store_true", dest="run_all_tests",
  42. help='Run all (unhidden) tests')
  43. group.add_argument('-R', '--skip-tests', required=False, action='store',
  44. nargs='+', dest="skips", default=None,
  45. help='Run all (unhidden) tests except the ones specified. Format should be <module>[.<class>[.<test_method>]]')
  46. group.add_argument('-r', '--run-tests', required=False, action='store',
  47. nargs='+', dest="run_tests", default=None,
  48. help='Select what tests to run (modules, classes or test methods). Format should be: <module>.<class>.<test_method>')
  49. group.add_argument('-m', '--list-modules', required=False,
  50. action="store_true", default=False,
  51. help='List all available test modules.')
  52. group.add_argument('--list-classes', required=False,
  53. action="store_true", default=False,
  54. help='List all available test classes.')
  55. group.add_argument('-l', '--list-tests', required=False,
  56. action="store_true", default=False,
  57. help='List all available tests.')
  58. parser.add_argument('-j', '--num-processes', dest='processes', action='store',
  59. type=int, help="number of processes to execute in parallel with")
  60. parser.add_argument('--machine', required=False, choices=['random', 'all'],
  61. help='Run tests on different machines (random/all).')
  62. parser.set_defaults(func=self.run)
  63. def _get_available_machines(self):
  64. machines = []
  65. bbpath = self.tc_kwargs['init']['td']['BBPATH'].split(':')
  66. for path in bbpath:
  67. found_machines = glob.glob(os.path.join(path, 'conf', 'machine', '*.conf'))
  68. if found_machines:
  69. for i in found_machines:
  70. # eg: '/home/<user>/poky/meta-intel/conf/machine/intel-core2-32.conf'
  71. machines.append(os.path.splitext(os.path.basename(i))[0])
  72. return machines
  73. def _get_cases_paths(self, bbpath):
  74. cases_paths = []
  75. for layer in bbpath:
  76. cases_dir = os.path.join(layer, 'lib', 'oeqa', 'selftest', 'cases')
  77. if os.path.isdir(cases_dir):
  78. cases_paths.append(cases_dir)
  79. return cases_paths
  80. def _process_args(self, logger, args):
  81. args.test_start_time = time.strftime("%Y%m%d%H%M%S")
  82. args.test_data_file = None
  83. args.CASES_PATHS = None
  84. bbvars = get_bb_vars()
  85. logdir = os.environ.get("BUILDDIR")
  86. if 'LOG_DIR' in bbvars:
  87. logdir = bbvars['LOG_DIR']
  88. bb.utils.mkdirhier(logdir)
  89. args.output_log = logdir + '/%s-results-%s.log' % (self.name, args.test_start_time)
  90. super(OESelftestTestContextExecutor, self)._process_args(logger, args)
  91. if args.list_modules:
  92. args.list_tests = 'module'
  93. elif args.list_classes:
  94. args.list_tests = 'class'
  95. elif args.list_tests:
  96. args.list_tests = 'name'
  97. self.tc_kwargs['init']['td'] = bbvars
  98. self.tc_kwargs['init']['machines'] = self._get_available_machines()
  99. builddir = os.environ.get("BUILDDIR")
  100. self.tc_kwargs['init']['config_paths'] = {}
  101. self.tc_kwargs['init']['config_paths']['testlayer_path'] = \
  102. get_test_layer()
  103. self.tc_kwargs['init']['config_paths']['builddir'] = builddir
  104. self.tc_kwargs['init']['config_paths']['localconf'] = \
  105. os.path.join(builddir, "conf/local.conf")
  106. self.tc_kwargs['init']['config_paths']['localconf_backup'] = \
  107. os.path.join(builddir, "conf/local.conf.orig")
  108. self.tc_kwargs['init']['config_paths']['localconf_class_backup'] = \
  109. os.path.join(builddir, "conf/local.conf.bk")
  110. self.tc_kwargs['init']['config_paths']['bblayers'] = \
  111. os.path.join(builddir, "conf/bblayers.conf")
  112. self.tc_kwargs['init']['config_paths']['bblayers_backup'] = \
  113. os.path.join(builddir, "conf/bblayers.conf.orig")
  114. self.tc_kwargs['init']['config_paths']['bblayers_class_backup'] = \
  115. os.path.join(builddir, "conf/bblayers.conf.bk")
  116. copyfile(self.tc_kwargs['init']['config_paths']['localconf'],
  117. self.tc_kwargs['init']['config_paths']['localconf_backup'])
  118. copyfile(self.tc_kwargs['init']['config_paths']['bblayers'],
  119. self.tc_kwargs['init']['config_paths']['bblayers_backup'])
  120. self.tc_kwargs['run']['skips'] = args.skips
  121. self.tc_kwargs['run']['processes'] = args.processes
  122. def _pre_run(self):
  123. def _check_required_env_variables(vars):
  124. for var in vars:
  125. if not os.environ.get(var):
  126. self.tc.logger.error("%s is not set. Did you forget to source your build environment setup script?" % var)
  127. raise OEQAPreRun
  128. def _check_presence_meta_selftest():
  129. builddir = os.environ.get("BUILDDIR")
  130. if os.getcwd() != builddir:
  131. self.tc.logger.info("Changing cwd to %s" % builddir)
  132. os.chdir(builddir)
  133. if not "meta-selftest" in self.tc.td["BBLAYERS"]:
  134. self.tc.logger.warning("meta-selftest layer not found in BBLAYERS, adding it")
  135. meta_selftestdir = os.path.join(
  136. self.tc.td["BBLAYERS_FETCH_DIR"], 'meta-selftest')
  137. if os.path.isdir(meta_selftestdir):
  138. runCmd("bitbake-layers add-layer %s" %meta_selftestdir)
  139. # reload data is needed because a meta-selftest layer was add
  140. self.tc.td = get_bb_vars()
  141. self.tc.config_paths['testlayer_path'] = get_test_layer()
  142. else:
  143. self.tc.logger.error("could not locate meta-selftest in:\n%s" % meta_selftestdir)
  144. raise OEQAPreRun
  145. def _add_layer_libs():
  146. bbpath = self.tc.td['BBPATH'].split(':')
  147. layer_libdirs = [p for p in (os.path.join(l, 'lib') \
  148. for l in bbpath) if os.path.exists(p)]
  149. if layer_libdirs:
  150. self.tc.logger.info("Adding layer libraries:")
  151. for l in layer_libdirs:
  152. self.tc.logger.info("\t%s" % l)
  153. sys.path.extend(layer_libdirs)
  154. importlib.reload(oeqa.selftest)
  155. _check_required_env_variables(["BUILDDIR"])
  156. _check_presence_meta_selftest()
  157. if "buildhistory.bbclass" in self.tc.td["BBINCLUDED"]:
  158. self.tc.logger.error("You have buildhistory enabled already and this isn't recommended for selftest, please disable it first.")
  159. raise OEQAPreRun
  160. if "rm_work.bbclass" in self.tc.td["BBINCLUDED"]:
  161. self.tc.logger.error("You have rm_work enabled which isn't recommended while running oe-selftest. Please disable it before continuing.")
  162. raise OEQAPreRun
  163. if "PRSERV_HOST" in self.tc.td:
  164. self.tc.logger.error("Please unset PRSERV_HOST in order to run oe-selftest")
  165. raise OEQAPreRun
  166. if "SANITY_TESTED_DISTROS" in self.tc.td:
  167. self.tc.logger.error("Please unset SANITY_TESTED_DISTROS in order to run oe-selftest")
  168. raise OEQAPreRun
  169. _add_layer_libs()
  170. self.tc.logger.info("Running bitbake -e to test the configuration is valid/parsable")
  171. runCmd("bitbake -e")
  172. def get_json_result_dir(self, args):
  173. json_result_dir = os.path.join(self.tc.td["LOG_DIR"], 'oeqa')
  174. if "OEQA_JSON_RESULT_DIR" in self.tc.td:
  175. json_result_dir = self.tc.td["OEQA_JSON_RESULT_DIR"]
  176. return json_result_dir
  177. def get_configuration(self, args):
  178. import platform
  179. from oeqa.utils.metadata import metadata_from_bb
  180. metadata = metadata_from_bb()
  181. configuration = {'TEST_TYPE': 'oeselftest',
  182. 'STARTTIME': args.test_start_time,
  183. 'MACHINE': self.tc.td["MACHINE"],
  184. 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'),
  185. 'HOST_NAME': metadata['hostname'],
  186. 'LAYERS': metadata['layers']}
  187. return configuration
  188. def get_result_id(self, configuration):
  189. return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['HOST_DISTRO'], configuration['MACHINE'], configuration['STARTTIME'])
  190. def _internal_run(self, logger, args):
  191. self.module_paths = self._get_cases_paths(
  192. self.tc_kwargs['init']['td']['BBPATH'].split(':'))
  193. self.tc = self._context_class(**self.tc_kwargs['init'])
  194. try:
  195. self.tc.loadTests(self.module_paths, **self.tc_kwargs['load'])
  196. except OEQATestNotFound as ex:
  197. logger.error(ex)
  198. sys.exit(1)
  199. if args.list_tests:
  200. rc = self.tc.listTests(args.list_tests, **self.tc_kwargs['list'])
  201. else:
  202. self._pre_run()
  203. rc = self.tc.runTests(**self.tc_kwargs['run'])
  204. configuration = self.get_configuration(args)
  205. rc.logDetails(self.get_json_result_dir(args),
  206. configuration,
  207. self.get_result_id(configuration))
  208. rc.logSummary(self.name)
  209. return rc
  210. def _signal_clean_handler(self, signum, frame):
  211. sys.exit(1)
  212. def run(self, logger, args):
  213. self._process_args(logger, args)
  214. signal.signal(signal.SIGTERM, self._signal_clean_handler)
  215. rc = None
  216. try:
  217. if args.machine:
  218. logger.info('Custom machine mode enabled. MACHINE set to %s' %
  219. args.machine)
  220. if args.machine == 'all':
  221. results = []
  222. for m in self.tc_kwargs['init']['machines']:
  223. self.tc_kwargs['run']['machine'] = m
  224. results.append(self._internal_run(logger, args))
  225. # XXX: the oe-selftest script only needs to know if one
  226. # machine run fails
  227. for r in results:
  228. rc = r
  229. if not r.wasSuccessful():
  230. break
  231. else:
  232. self.tc_kwargs['run']['machine'] = args.machine
  233. return self._internal_run(logger, args)
  234. else:
  235. self.tc_kwargs['run']['machine'] = args.machine
  236. rc = self._internal_run(logger, args)
  237. finally:
  238. config_paths = self.tc_kwargs['init']['config_paths']
  239. if os.path.exists(config_paths['localconf_backup']):
  240. copyfile(config_paths['localconf_backup'],
  241. config_paths['localconf'])
  242. os.remove(config_paths['localconf_backup'])
  243. if os.path.exists(config_paths['bblayers_backup']):
  244. copyfile(config_paths['bblayers_backup'],
  245. config_paths['bblayers'])
  246. os.remove(config_paths['bblayers_backup'])
  247. if os.path.exists(config_paths['localconf_class_backup']):
  248. os.remove(config_paths['localconf_class_backup'])
  249. if os.path.exists(config_paths['bblayers_class_backup']):
  250. os.remove(config_paths['bblayers_class_backup'])
  251. output_link = os.path.join(os.path.dirname(args.output_log),
  252. "%s-results.log" % self.name)
  253. if os.path.lexists(output_link):
  254. os.remove(output_link)
  255. os.symlink(args.output_log, output_link)
  256. return rc
  257. _executor_class = OESelftestTestContextExecutor