blob: 23f7d71bdbc5dad2c1d15da26b6afc2b9e9855b3 [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
Andrew Geissler82c905d2020-04-13 13:39:40 -050012import subprocess
Andrew Geissler4ed12e12020-06-05 18:00:41 -050013import unittest
Brad Bishopd7bf8c12018-02-25 22:55:05 -050014from random import choice
15
16import oeqa
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080017import oe
Andrew Geissler82c905d2020-04-13 13:39:40 -050018import bb.utils
Brad Bishopd7bf8c12018-02-25 22:55:05 -050019
20from oeqa.core.context import OETestContext, OETestContextExecutor
21from oeqa.core.exception import OEQAPreRun, OEQATestNotFound
22
23from oeqa.utils.commands import runCmd, get_bb_vars, get_test_layer
24
Andrew Geissler475cb722020-07-10 16:00:51 -050025class NonConcurrentTestSuite(unittest.TestSuite):
26 def __init__(self, suite, processes, setupfunc, removefunc):
27 super().__init__([suite])
28 self.processes = processes
29 self.suite = suite
30 self.setupfunc = setupfunc
31 self.removefunc = removefunc
32
33 def run(self, result):
34 (builddir, newbuilddir) = self.setupfunc("-st", None, self.suite)
35 ret = super().run(result)
36 os.chdir(builddir)
37 if newbuilddir and ret.wasSuccessful():
38 self.removefunc(newbuilddir)
39
40def removebuilddir(d):
41 delay = 5
42 while delay and os.path.exists(d + "/bitbake.lock"):
43 time.sleep(1)
44 delay = delay - 1
45 # Deleting these directories takes a lot of time, use autobuilder
46 # clobberdir if its available
47 clobberdir = os.path.expanduser("~/yocto-autobuilder-helper/janitor/clobberdir")
48 if os.path.exists(clobberdir):
49 try:
50 subprocess.check_call([clobberdir, d])
51 return
52 except subprocess.CalledProcessError:
53 pass
54 bb.utils.prunedir(d, ionice=True)
55
Brad Bishopd7bf8c12018-02-25 22:55:05 -050056class OESelftestTestContext(OETestContext):
Andrew Geissler4ed12e12020-06-05 18:00:41 -050057 def __init__(self, td=None, logger=None, machines=None, config_paths=None, newbuilddir=None):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050058 super(OESelftestTestContext, self).__init__(td, logger)
59
60 self.machines = machines
61 self.custommachine = None
62 self.config_paths = config_paths
Andrew Geissler4ed12e12020-06-05 18:00:41 -050063 self.newbuilddir = newbuilddir
Brad Bishopd7bf8c12018-02-25 22:55:05 -050064
Andrew Geissler82c905d2020-04-13 13:39:40 -050065 def setup_builddir(self, suffix, selftestdir, suite):
66 builddir = os.environ['BUILDDIR']
67 if not selftestdir:
68 selftestdir = get_test_layer()
Andrew Geissler4ed12e12020-06-05 18:00:41 -050069 if self.newbuilddir:
70 newbuilddir = os.path.join(self.newbuilddir, 'build' + suffix)
71 else:
72 newbuilddir = builddir + suffix
Andrew Geissler82c905d2020-04-13 13:39:40 -050073 newselftestdir = newbuilddir + "/meta-selftest"
74
75 if os.path.exists(newbuilddir):
76 self.logger.error("Build directory %s already exists, aborting" % newbuilddir)
77 sys.exit(1)
78
79 bb.utils.mkdirhier(newbuilddir)
80 oe.path.copytree(builddir + "/conf", newbuilddir + "/conf")
81 oe.path.copytree(builddir + "/cache", newbuilddir + "/cache")
82 oe.path.copytree(selftestdir, newselftestdir)
83
84 for e in os.environ:
85 if builddir + "/" in os.environ[e] or os.environ[e].endswith(builddir):
86 os.environ[e] = os.environ[e].replace(builddir, newbuilddir)
87
88 subprocess.check_output("git init; git add *; git commit -a -m 'initial'", cwd=newselftestdir, shell=True)
89
90 # Tried to used bitbake-layers add/remove but it requires recipe parsing and hence is too slow
91 subprocess.check_output("sed %s/conf/bblayers.conf -i -e 's#%s#%s#g'" % (newbuilddir, selftestdir, newselftestdir), cwd=newbuilddir, shell=True)
92
93 os.chdir(newbuilddir)
94
Andrew Geissler4ed12e12020-06-05 18:00:41 -050095 def patch_test(t):
Andrew Geissler82c905d2020-04-13 13:39:40 -050096 if not hasattr(t, "tc"):
Andrew Geissler4ed12e12020-06-05 18:00:41 -050097 return
Andrew Geissler82c905d2020-04-13 13:39:40 -050098 cp = t.tc.config_paths
99 for p in cp:
100 if selftestdir in cp[p] and newselftestdir not in cp[p]:
101 cp[p] = cp[p].replace(selftestdir, newselftestdir)
102 if builddir in cp[p] and newbuilddir not in cp[p]:
103 cp[p] = cp[p].replace(builddir, newbuilddir)
104
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500105 def patch_suite(s):
106 for x in s:
107 if isinstance(x, unittest.TestSuite):
108 patch_suite(x)
109 else:
110 patch_test(x)
111
112 patch_suite(suite)
113
Andrew Geissler82c905d2020-04-13 13:39:40 -0500114 return (builddir, newbuilddir)
115
116 def prepareSuite(self, suites, processes):
117 if processes:
118 from oeqa.core.utils.concurrencytest import ConcurrentTestSuite
119
Andrew Geissler475cb722020-07-10 16:00:51 -0500120 return ConcurrentTestSuite(suites, processes, self.setup_builddir, removebuilddir)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500121 else:
Andrew Geissler475cb722020-07-10 16:00:51 -0500122 return NonConcurrentTestSuite(suites, processes, self.setup_builddir, removebuilddir)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500123
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800124 def runTests(self, processes=None, machine=None, skips=[]):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500125 if machine:
126 self.custommachine = machine
127 if machine == 'random':
128 self.custommachine = choice(self.machines)
129 self.logger.info('Run tests with custom MACHINE set to: %s' % \
130 self.custommachine)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800131 return super(OESelftestTestContext, self).runTests(processes, skips)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500132
133 def listTests(self, display_type, machine=None):
134 return super(OESelftestTestContext, self).listTests(display_type)
135
136class OESelftestTestContextExecutor(OETestContextExecutor):
137 _context_class = OESelftestTestContext
138 _script_executor = 'oe-selftest'
139
140 name = 'oe-selftest'
141 help = 'oe-selftest test component'
142 description = 'Executes selftest tests'
143
144 def register_commands(self, logger, parser):
145 group = parser.add_mutually_exclusive_group(required=True)
146
147 group.add_argument('-a', '--run-all-tests', default=False,
148 action="store_true", dest="run_all_tests",
149 help='Run all (unhidden) tests')
150 group.add_argument('-R', '--skip-tests', required=False, action='store',
151 nargs='+', dest="skips", default=None,
152 help='Run all (unhidden) tests except the ones specified. Format should be <module>[.<class>[.<test_method>]]')
153 group.add_argument('-r', '--run-tests', required=False, action='store',
154 nargs='+', dest="run_tests", default=None,
155 help='Select what tests to run (modules, classes or test methods). Format should be: <module>.<class>.<test_method>')
156
157 group.add_argument('-m', '--list-modules', required=False,
158 action="store_true", default=False,
159 help='List all available test modules.')
160 group.add_argument('--list-classes', required=False,
161 action="store_true", default=False,
162 help='List all available test classes.')
163 group.add_argument('-l', '--list-tests', required=False,
164 action="store_true", default=False,
165 help='List all available tests.')
166
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800167 parser.add_argument('-j', '--num-processes', dest='processes', action='store',
168 type=int, help="number of processes to execute in parallel with")
169
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500170 parser.add_argument('--machine', required=False, choices=['random', 'all'],
171 help='Run tests on different machines (random/all).')
Brad Bishop79641f22019-09-10 07:20:22 -0400172
Brad Bishopacc069e2019-09-13 06:48:36 -0400173 parser.add_argument('-t', '--select-tag', dest="select_tags",
174 action='append', default=None,
175 help='Filter all (unhidden) tests to any that match any of the specified tag(s).')
176 parser.add_argument('-T', '--exclude-tag', dest="exclude_tags",
177 action='append', default=None,
178 help='Exclude all (unhidden) tests that match any of the specified tag(s). (exclude applies before select)')
Brad Bishop79641f22019-09-10 07:20:22 -0400179
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500180 parser.add_argument('-B', '--newbuilddir', help='New build directory to use for tests.')
181 parser.add_argument('-v', '--verbose', action='store_true')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500182 parser.set_defaults(func=self.run)
183
184 def _get_available_machines(self):
185 machines = []
186
187 bbpath = self.tc_kwargs['init']['td']['BBPATH'].split(':')
188
189 for path in bbpath:
190 found_machines = glob.glob(os.path.join(path, 'conf', 'machine', '*.conf'))
191 if found_machines:
192 for i in found_machines:
193 # eg: '/home/<user>/poky/meta-intel/conf/machine/intel-core2-32.conf'
194 machines.append(os.path.splitext(os.path.basename(i))[0])
195
196 return machines
197
198 def _get_cases_paths(self, bbpath):
199 cases_paths = []
200 for layer in bbpath:
201 cases_dir = os.path.join(layer, 'lib', 'oeqa', 'selftest', 'cases')
202 if os.path.isdir(cases_dir):
203 cases_paths.append(cases_dir)
204 return cases_paths
205
206 def _process_args(self, logger, args):
Brad Bishopf86d0552018-12-04 14:18:15 -0800207 args.test_start_time = time.strftime("%Y%m%d%H%M%S")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500208 args.test_data_file = None
209 args.CASES_PATHS = None
210
Brad Bishopf86d0552018-12-04 14:18:15 -0800211 bbvars = get_bb_vars()
212 logdir = os.environ.get("BUILDDIR")
213 if 'LOG_DIR' in bbvars:
214 logdir = bbvars['LOG_DIR']
Brad Bishop19323692019-04-05 15:28:33 -0400215 bb.utils.mkdirhier(logdir)
Brad Bishopf86d0552018-12-04 14:18:15 -0800216 args.output_log = logdir + '/%s-results-%s.log' % (self.name, args.test_start_time)
217
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500218 super(OESelftestTestContextExecutor, self)._process_args(logger, args)
219
220 if args.list_modules:
221 args.list_tests = 'module'
222 elif args.list_classes:
223 args.list_tests = 'class'
224 elif args.list_tests:
225 args.list_tests = 'name'
226
Brad Bishopf86d0552018-12-04 14:18:15 -0800227 self.tc_kwargs['init']['td'] = bbvars
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500228 self.tc_kwargs['init']['machines'] = self._get_available_machines()
229
230 builddir = os.environ.get("BUILDDIR")
231 self.tc_kwargs['init']['config_paths'] = {}
Andrew Geissler82c905d2020-04-13 13:39:40 -0500232 self.tc_kwargs['init']['config_paths']['testlayer_path'] = get_test_layer()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500233 self.tc_kwargs['init']['config_paths']['builddir'] = builddir
Andrew Geissler82c905d2020-04-13 13:39:40 -0500234 self.tc_kwargs['init']['config_paths']['localconf'] = os.path.join(builddir, "conf/local.conf")
235 self.tc_kwargs['init']['config_paths']['bblayers'] = os.path.join(builddir, "conf/bblayers.conf")
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500236 self.tc_kwargs['init']['newbuilddir'] = args.newbuilddir
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500237
Brad Bishop79641f22019-09-10 07:20:22 -0400238 def tag_filter(tags):
239 if args.exclude_tags:
240 if any(tag in args.exclude_tags for tag in tags):
241 return True
242 if args.select_tags:
243 if not tags or not any(tag in args.select_tags for tag in tags):
244 return True
245 return False
246
247 if args.select_tags or args.exclude_tags:
248 self.tc_kwargs['load']['tags_filter'] = tag_filter
249
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500250 self.tc_kwargs['run']['skips'] = args.skips
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800251 self.tc_kwargs['run']['processes'] = args.processes
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500252
253 def _pre_run(self):
254 def _check_required_env_variables(vars):
255 for var in vars:
256 if not os.environ.get(var):
257 self.tc.logger.error("%s is not set. Did you forget to source your build environment setup script?" % var)
258 raise OEQAPreRun
259
260 def _check_presence_meta_selftest():
261 builddir = os.environ.get("BUILDDIR")
262 if os.getcwd() != builddir:
263 self.tc.logger.info("Changing cwd to %s" % builddir)
264 os.chdir(builddir)
265
266 if not "meta-selftest" in self.tc.td["BBLAYERS"]:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800267 self.tc.logger.warning("meta-selftest layer not found in BBLAYERS, adding it")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500268 meta_selftestdir = os.path.join(
269 self.tc.td["BBLAYERS_FETCH_DIR"], 'meta-selftest')
270 if os.path.isdir(meta_selftestdir):
271 runCmd("bitbake-layers add-layer %s" %meta_selftestdir)
272 # reload data is needed because a meta-selftest layer was add
273 self.tc.td = get_bb_vars()
274 self.tc.config_paths['testlayer_path'] = get_test_layer()
275 else:
276 self.tc.logger.error("could not locate meta-selftest in:\n%s" % meta_selftestdir)
277 raise OEQAPreRun
278
279 def _add_layer_libs():
280 bbpath = self.tc.td['BBPATH'].split(':')
281 layer_libdirs = [p for p in (os.path.join(l, 'lib') \
282 for l in bbpath) if os.path.exists(p)]
283 if layer_libdirs:
284 self.tc.logger.info("Adding layer libraries:")
285 for l in layer_libdirs:
286 self.tc.logger.info("\t%s" % l)
287
288 sys.path.extend(layer_libdirs)
Brad Bishopf86d0552018-12-04 14:18:15 -0800289 importlib.reload(oeqa.selftest)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500290
291 _check_required_env_variables(["BUILDDIR"])
292 _check_presence_meta_selftest()
293
294 if "buildhistory.bbclass" in self.tc.td["BBINCLUDED"]:
295 self.tc.logger.error("You have buildhistory enabled already and this isn't recommended for selftest, please disable it first.")
296 raise OEQAPreRun
297
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800298 if "rm_work.bbclass" in self.tc.td["BBINCLUDED"]:
299 self.tc.logger.error("You have rm_work enabled which isn't recommended while running oe-selftest. Please disable it before continuing.")
300 raise OEQAPreRun
301
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500302 if "PRSERV_HOST" in self.tc.td:
303 self.tc.logger.error("Please unset PRSERV_HOST in order to run oe-selftest")
304 raise OEQAPreRun
305
306 if "SANITY_TESTED_DISTROS" in self.tc.td:
307 self.tc.logger.error("Please unset SANITY_TESTED_DISTROS in order to run oe-selftest")
308 raise OEQAPreRun
309
310 _add_layer_libs()
311
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800312 self.tc.logger.info("Running bitbake -e to test the configuration is valid/parsable")
313 runCmd("bitbake -e")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500314
Brad Bishopf86d0552018-12-04 14:18:15 -0800315 def get_json_result_dir(self, args):
316 json_result_dir = os.path.join(self.tc.td["LOG_DIR"], 'oeqa')
317 if "OEQA_JSON_RESULT_DIR" in self.tc.td:
318 json_result_dir = self.tc.td["OEQA_JSON_RESULT_DIR"]
319
320 return json_result_dir
321
322 def get_configuration(self, args):
323 import platform
324 from oeqa.utils.metadata import metadata_from_bb
325 metadata = metadata_from_bb()
326 configuration = {'TEST_TYPE': 'oeselftest',
327 'STARTTIME': args.test_start_time,
328 'MACHINE': self.tc.td["MACHINE"],
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800329 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'),
Brad Bishopf86d0552018-12-04 14:18:15 -0800330 'HOST_NAME': metadata['hostname'],
331 'LAYERS': metadata['layers']}
332 return configuration
333
334 def get_result_id(self, configuration):
335 return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['HOST_DISTRO'], configuration['MACHINE'], configuration['STARTTIME'])
336
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500337 def _internal_run(self, logger, args):
338 self.module_paths = self._get_cases_paths(
339 self.tc_kwargs['init']['td']['BBPATH'].split(':'))
340
341 self.tc = self._context_class(**self.tc_kwargs['init'])
342 try:
343 self.tc.loadTests(self.module_paths, **self.tc_kwargs['load'])
344 except OEQATestNotFound as ex:
345 logger.error(ex)
346 sys.exit(1)
347
348 if args.list_tests:
349 rc = self.tc.listTests(args.list_tests, **self.tc_kwargs['list'])
350 else:
351 self._pre_run()
352 rc = self.tc.runTests(**self.tc_kwargs['run'])
Brad Bishopf86d0552018-12-04 14:18:15 -0800353 configuration = self.get_configuration(args)
354 rc.logDetails(self.get_json_result_dir(args),
355 configuration,
356 self.get_result_id(configuration))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500357 rc.logSummary(self.name)
358
359 return rc
360
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500361 def run(self, logger, args):
362 self._process_args(logger, args)
363
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500364 rc = None
365 try:
366 if args.machine:
367 logger.info('Custom machine mode enabled. MACHINE set to %s' %
368 args.machine)
369
370 if args.machine == 'all':
371 results = []
372 for m in self.tc_kwargs['init']['machines']:
373 self.tc_kwargs['run']['machine'] = m
374 results.append(self._internal_run(logger, args))
375
376 # XXX: the oe-selftest script only needs to know if one
377 # machine run fails
378 for r in results:
379 rc = r
380 if not r.wasSuccessful():
381 break
382
383 else:
384 self.tc_kwargs['run']['machine'] = args.machine
385 return self._internal_run(logger, args)
386
387 else:
388 self.tc_kwargs['run']['machine'] = args.machine
389 rc = self._internal_run(logger, args)
390 finally:
391 config_paths = self.tc_kwargs['init']['config_paths']
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500392
393 output_link = os.path.join(os.path.dirname(args.output_log),
394 "%s-results.log" % self.name)
Brad Bishopf86d0552018-12-04 14:18:15 -0800395 if os.path.lexists(output_link):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500396 os.remove(output_link)
397 os.symlink(args.output_log, output_link)
398
399 return rc
400
401_executor_class = OESelftestTestContextExecutor