blob: d279994ddfdc4501c1aaa350b145b58cf34e2cc6 [file] [log] [blame]
Brad Bishopc342db32019-05-15 21:57:59 -04001#
Brad Bishopd7bf8c12018-02-25 22:55:05 -05002# Copyright (C) 2017 Intel Corporation
Brad Bishopc342db32019-05-15 21:57:59 -04003#
4# SPDX-License-Identifier: MIT
5#
Brad Bishopd7bf8c12018-02-25 22:55:05 -05006
7import os
8import time
9import glob
10import sys
Brad Bishopf86d0552018-12-04 14:18:15 -080011import importlib
Brad Bishopd7bf8c12018-02-25 22:55:05 -050012import signal
13from shutil import copyfile
14from random import choice
15
16import oeqa
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080017import oe
Brad Bishopd7bf8c12018-02-25 22:55:05 -050018
19from oeqa.core.context import OETestContext, OETestContextExecutor
20from oeqa.core.exception import OEQAPreRun, OEQATestNotFound
21
22from oeqa.utils.commands import runCmd, get_bb_vars, get_test_layer
23
24class OESelftestTestContext(OETestContext):
25 def __init__(self, td=None, logger=None, machines=None, config_paths=None):
26 super(OESelftestTestContext, self).__init__(td, logger)
27
28 self.machines = machines
29 self.custommachine = None
30 self.config_paths = config_paths
31
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080032 def runTests(self, processes=None, machine=None, skips=[]):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050033 if machine:
34 self.custommachine = machine
35 if machine == 'random':
36 self.custommachine = choice(self.machines)
37 self.logger.info('Run tests with custom MACHINE set to: %s' % \
38 self.custommachine)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080039 return super(OESelftestTestContext, self).runTests(processes, skips)
Brad Bishopd7bf8c12018-02-25 22:55:05 -050040
41 def listTests(self, display_type, machine=None):
42 return super(OESelftestTestContext, self).listTests(display_type)
43
44class OESelftestTestContextExecutor(OETestContextExecutor):
45 _context_class = OESelftestTestContext
46 _script_executor = 'oe-selftest'
47
48 name = 'oe-selftest'
49 help = 'oe-selftest test component'
50 description = 'Executes selftest tests'
51
52 def register_commands(self, logger, parser):
53 group = parser.add_mutually_exclusive_group(required=True)
54
55 group.add_argument('-a', '--run-all-tests', default=False,
56 action="store_true", dest="run_all_tests",
57 help='Run all (unhidden) tests')
58 group.add_argument('-R', '--skip-tests', required=False, action='store',
59 nargs='+', dest="skips", default=None,
60 help='Run all (unhidden) tests except the ones specified. Format should be <module>[.<class>[.<test_method>]]')
61 group.add_argument('-r', '--run-tests', required=False, action='store',
62 nargs='+', dest="run_tests", default=None,
63 help='Select what tests to run (modules, classes or test methods). Format should be: <module>.<class>.<test_method>')
64
65 group.add_argument('-m', '--list-modules', required=False,
66 action="store_true", default=False,
67 help='List all available test modules.')
68 group.add_argument('--list-classes', required=False,
69 action="store_true", default=False,
70 help='List all available test classes.')
71 group.add_argument('-l', '--list-tests', required=False,
72 action="store_true", default=False,
73 help='List all available tests.')
74
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080075 parser.add_argument('-j', '--num-processes', dest='processes', action='store',
76 type=int, help="number of processes to execute in parallel with")
77
Brad Bishopd7bf8c12018-02-25 22:55:05 -050078 parser.add_argument('--machine', required=False, choices=['random', 'all'],
79 help='Run tests on different machines (random/all).')
80
81 parser.set_defaults(func=self.run)
82
83 def _get_available_machines(self):
84 machines = []
85
86 bbpath = self.tc_kwargs['init']['td']['BBPATH'].split(':')
87
88 for path in bbpath:
89 found_machines = glob.glob(os.path.join(path, 'conf', 'machine', '*.conf'))
90 if found_machines:
91 for i in found_machines:
92 # eg: '/home/<user>/poky/meta-intel/conf/machine/intel-core2-32.conf'
93 machines.append(os.path.splitext(os.path.basename(i))[0])
94
95 return machines
96
97 def _get_cases_paths(self, bbpath):
98 cases_paths = []
99 for layer in bbpath:
100 cases_dir = os.path.join(layer, 'lib', 'oeqa', 'selftest', 'cases')
101 if os.path.isdir(cases_dir):
102 cases_paths.append(cases_dir)
103 return cases_paths
104
105 def _process_args(self, logger, args):
Brad Bishopf86d0552018-12-04 14:18:15 -0800106 args.test_start_time = time.strftime("%Y%m%d%H%M%S")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500107 args.test_data_file = None
108 args.CASES_PATHS = None
109
Brad Bishopf86d0552018-12-04 14:18:15 -0800110 bbvars = get_bb_vars()
111 logdir = os.environ.get("BUILDDIR")
112 if 'LOG_DIR' in bbvars:
113 logdir = bbvars['LOG_DIR']
Brad Bishop19323692019-04-05 15:28:33 -0400114 bb.utils.mkdirhier(logdir)
Brad Bishopf86d0552018-12-04 14:18:15 -0800115 args.output_log = logdir + '/%s-results-%s.log' % (self.name, args.test_start_time)
116
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500117 super(OESelftestTestContextExecutor, self)._process_args(logger, args)
118
119 if args.list_modules:
120 args.list_tests = 'module'
121 elif args.list_classes:
122 args.list_tests = 'class'
123 elif args.list_tests:
124 args.list_tests = 'name'
125
Brad Bishopf86d0552018-12-04 14:18:15 -0800126 self.tc_kwargs['init']['td'] = bbvars
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500127 self.tc_kwargs['init']['machines'] = self._get_available_machines()
128
129 builddir = os.environ.get("BUILDDIR")
130 self.tc_kwargs['init']['config_paths'] = {}
131 self.tc_kwargs['init']['config_paths']['testlayer_path'] = \
132 get_test_layer()
133 self.tc_kwargs['init']['config_paths']['builddir'] = builddir
134 self.tc_kwargs['init']['config_paths']['localconf'] = \
135 os.path.join(builddir, "conf/local.conf")
136 self.tc_kwargs['init']['config_paths']['localconf_backup'] = \
137 os.path.join(builddir, "conf/local.conf.orig")
138 self.tc_kwargs['init']['config_paths']['localconf_class_backup'] = \
139 os.path.join(builddir, "conf/local.conf.bk")
140 self.tc_kwargs['init']['config_paths']['bblayers'] = \
141 os.path.join(builddir, "conf/bblayers.conf")
142 self.tc_kwargs['init']['config_paths']['bblayers_backup'] = \
143 os.path.join(builddir, "conf/bblayers.conf.orig")
144 self.tc_kwargs['init']['config_paths']['bblayers_class_backup'] = \
145 os.path.join(builddir, "conf/bblayers.conf.bk")
146
147 copyfile(self.tc_kwargs['init']['config_paths']['localconf'],
148 self.tc_kwargs['init']['config_paths']['localconf_backup'])
149 copyfile(self.tc_kwargs['init']['config_paths']['bblayers'],
150 self.tc_kwargs['init']['config_paths']['bblayers_backup'])
151
152 self.tc_kwargs['run']['skips'] = args.skips
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800153 self.tc_kwargs['run']['processes'] = args.processes
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500154
155 def _pre_run(self):
156 def _check_required_env_variables(vars):
157 for var in vars:
158 if not os.environ.get(var):
159 self.tc.logger.error("%s is not set. Did you forget to source your build environment setup script?" % var)
160 raise OEQAPreRun
161
162 def _check_presence_meta_selftest():
163 builddir = os.environ.get("BUILDDIR")
164 if os.getcwd() != builddir:
165 self.tc.logger.info("Changing cwd to %s" % builddir)
166 os.chdir(builddir)
167
168 if not "meta-selftest" in self.tc.td["BBLAYERS"]:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800169 self.tc.logger.warning("meta-selftest layer not found in BBLAYERS, adding it")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500170 meta_selftestdir = os.path.join(
171 self.tc.td["BBLAYERS_FETCH_DIR"], 'meta-selftest')
172 if os.path.isdir(meta_selftestdir):
173 runCmd("bitbake-layers add-layer %s" %meta_selftestdir)
174 # reload data is needed because a meta-selftest layer was add
175 self.tc.td = get_bb_vars()
176 self.tc.config_paths['testlayer_path'] = get_test_layer()
177 else:
178 self.tc.logger.error("could not locate meta-selftest in:\n%s" % meta_selftestdir)
179 raise OEQAPreRun
180
181 def _add_layer_libs():
182 bbpath = self.tc.td['BBPATH'].split(':')
183 layer_libdirs = [p for p in (os.path.join(l, 'lib') \
184 for l in bbpath) if os.path.exists(p)]
185 if layer_libdirs:
186 self.tc.logger.info("Adding layer libraries:")
187 for l in layer_libdirs:
188 self.tc.logger.info("\t%s" % l)
189
190 sys.path.extend(layer_libdirs)
Brad Bishopf86d0552018-12-04 14:18:15 -0800191 importlib.reload(oeqa.selftest)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500192
193 _check_required_env_variables(["BUILDDIR"])
194 _check_presence_meta_selftest()
195
196 if "buildhistory.bbclass" in self.tc.td["BBINCLUDED"]:
197 self.tc.logger.error("You have buildhistory enabled already and this isn't recommended for selftest, please disable it first.")
198 raise OEQAPreRun
199
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800200 if "rm_work.bbclass" in self.tc.td["BBINCLUDED"]:
201 self.tc.logger.error("You have rm_work enabled which isn't recommended while running oe-selftest. Please disable it before continuing.")
202 raise OEQAPreRun
203
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500204 if "PRSERV_HOST" in self.tc.td:
205 self.tc.logger.error("Please unset PRSERV_HOST in order to run oe-selftest")
206 raise OEQAPreRun
207
208 if "SANITY_TESTED_DISTROS" in self.tc.td:
209 self.tc.logger.error("Please unset SANITY_TESTED_DISTROS in order to run oe-selftest")
210 raise OEQAPreRun
211
212 _add_layer_libs()
213
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800214 self.tc.logger.info("Running bitbake -e to test the configuration is valid/parsable")
215 runCmd("bitbake -e")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500216
Brad Bishopf86d0552018-12-04 14:18:15 -0800217 def get_json_result_dir(self, args):
218 json_result_dir = os.path.join(self.tc.td["LOG_DIR"], 'oeqa')
219 if "OEQA_JSON_RESULT_DIR" in self.tc.td:
220 json_result_dir = self.tc.td["OEQA_JSON_RESULT_DIR"]
221
222 return json_result_dir
223
224 def get_configuration(self, args):
225 import platform
226 from oeqa.utils.metadata import metadata_from_bb
227 metadata = metadata_from_bb()
228 configuration = {'TEST_TYPE': 'oeselftest',
229 'STARTTIME': args.test_start_time,
230 'MACHINE': self.tc.td["MACHINE"],
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800231 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'),
Brad Bishopf86d0552018-12-04 14:18:15 -0800232 'HOST_NAME': metadata['hostname'],
233 'LAYERS': metadata['layers']}
234 return configuration
235
236 def get_result_id(self, configuration):
237 return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['HOST_DISTRO'], configuration['MACHINE'], configuration['STARTTIME'])
238
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500239 def _internal_run(self, logger, args):
240 self.module_paths = self._get_cases_paths(
241 self.tc_kwargs['init']['td']['BBPATH'].split(':'))
242
243 self.tc = self._context_class(**self.tc_kwargs['init'])
244 try:
245 self.tc.loadTests(self.module_paths, **self.tc_kwargs['load'])
246 except OEQATestNotFound as ex:
247 logger.error(ex)
248 sys.exit(1)
249
250 if args.list_tests:
251 rc = self.tc.listTests(args.list_tests, **self.tc_kwargs['list'])
252 else:
253 self._pre_run()
254 rc = self.tc.runTests(**self.tc_kwargs['run'])
Brad Bishopf86d0552018-12-04 14:18:15 -0800255 configuration = self.get_configuration(args)
256 rc.logDetails(self.get_json_result_dir(args),
257 configuration,
258 self.get_result_id(configuration))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500259 rc.logSummary(self.name)
260
261 return rc
262
263 def _signal_clean_handler(self, signum, frame):
264 sys.exit(1)
265
266 def run(self, logger, args):
267 self._process_args(logger, args)
268
269 signal.signal(signal.SIGTERM, self._signal_clean_handler)
270
271 rc = None
272 try:
273 if args.machine:
274 logger.info('Custom machine mode enabled. MACHINE set to %s' %
275 args.machine)
276
277 if args.machine == 'all':
278 results = []
279 for m in self.tc_kwargs['init']['machines']:
280 self.tc_kwargs['run']['machine'] = m
281 results.append(self._internal_run(logger, args))
282
283 # XXX: the oe-selftest script only needs to know if one
284 # machine run fails
285 for r in results:
286 rc = r
287 if not r.wasSuccessful():
288 break
289
290 else:
291 self.tc_kwargs['run']['machine'] = args.machine
292 return self._internal_run(logger, args)
293
294 else:
295 self.tc_kwargs['run']['machine'] = args.machine
296 rc = self._internal_run(logger, args)
297 finally:
298 config_paths = self.tc_kwargs['init']['config_paths']
299 if os.path.exists(config_paths['localconf_backup']):
300 copyfile(config_paths['localconf_backup'],
301 config_paths['localconf'])
302 os.remove(config_paths['localconf_backup'])
303
304 if os.path.exists(config_paths['bblayers_backup']):
305 copyfile(config_paths['bblayers_backup'],
306 config_paths['bblayers'])
307 os.remove(config_paths['bblayers_backup'])
308
309 if os.path.exists(config_paths['localconf_class_backup']):
310 os.remove(config_paths['localconf_class_backup'])
311 if os.path.exists(config_paths['bblayers_class_backup']):
312 os.remove(config_paths['bblayers_class_backup'])
313
314 output_link = os.path.join(os.path.dirname(args.output_log),
315 "%s-results.log" % self.name)
Brad Bishopf86d0552018-12-04 14:18:15 -0800316 if os.path.lexists(output_link):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500317 os.remove(output_link)
318 os.symlink(args.output_log, output_link)
319
320 return rc
321
322_executor_class = OESelftestTestContextExecutor