blob: ab13131f2971aaaf789296f6e1bf49fb569fb190 [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 Geissler6aa7eec2023-03-03 12:41:14 -060025OESELFTEST_METADATA=["run_all_tests", "run_tests", "skips", "machine", "select_tags", "exclude_tags"]
26
27def get_oeselftest_metadata(args):
28 result = {}
29 raw_args = vars(args)
30 for metadata in OESELFTEST_METADATA:
31 if metadata in raw_args:
32 result[metadata] = raw_args[metadata]
33
34 return result
35
Andrew Geissler475cb722020-07-10 16:00:51 -050036class NonConcurrentTestSuite(unittest.TestSuite):
37 def __init__(self, suite, processes, setupfunc, removefunc):
38 super().__init__([suite])
39 self.processes = processes
40 self.suite = suite
41 self.setupfunc = setupfunc
42 self.removefunc = removefunc
43
44 def run(self, result):
45 (builddir, newbuilddir) = self.setupfunc("-st", None, self.suite)
46 ret = super().run(result)
47 os.chdir(builddir)
Andrew Geisslerd1e89492021-02-12 15:35:20 -060048 if newbuilddir and ret.wasSuccessful() and self.removefunc:
Andrew Geissler475cb722020-07-10 16:00:51 -050049 self.removefunc(newbuilddir)
50
51def removebuilddir(d):
52 delay = 5
Andrew Geisslereff27472021-10-29 15:35:00 -050053 while delay and (os.path.exists(d + "/bitbake.lock") or os.path.exists(d + "/cache/hashserv.db-wal")):
Andrew Geissler475cb722020-07-10 16:00:51 -050054 time.sleep(1)
55 delay = delay - 1
56 # Deleting these directories takes a lot of time, use autobuilder
57 # clobberdir if its available
58 clobberdir = os.path.expanduser("~/yocto-autobuilder-helper/janitor/clobberdir")
59 if os.path.exists(clobberdir):
60 try:
61 subprocess.check_call([clobberdir, d])
62 return
63 except subprocess.CalledProcessError:
64 pass
65 bb.utils.prunedir(d, ionice=True)
66
Brad Bishopd7bf8c12018-02-25 22:55:05 -050067class OESelftestTestContext(OETestContext):
Andrew Geisslerd1e89492021-02-12 15:35:20 -060068 def __init__(self, td=None, logger=None, machines=None, config_paths=None, newbuilddir=None, keep_builddir=None):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050069 super(OESelftestTestContext, self).__init__(td, logger)
70
71 self.machines = machines
72 self.custommachine = None
73 self.config_paths = config_paths
Andrew Geissler4ed12e12020-06-05 18:00:41 -050074 self.newbuilddir = newbuilddir
Brad Bishopd7bf8c12018-02-25 22:55:05 -050075
Andrew Geisslerd1e89492021-02-12 15:35:20 -060076 if keep_builddir:
77 self.removebuilddir = None
78 else:
79 self.removebuilddir = removebuilddir
80
Andrew Geissler82c905d2020-04-13 13:39:40 -050081 def setup_builddir(self, suffix, selftestdir, suite):
82 builddir = os.environ['BUILDDIR']
83 if not selftestdir:
84 selftestdir = get_test_layer()
Andrew Geissler4ed12e12020-06-05 18:00:41 -050085 if self.newbuilddir:
86 newbuilddir = os.path.join(self.newbuilddir, 'build' + suffix)
87 else:
88 newbuilddir = builddir + suffix
Andrew Geissler82c905d2020-04-13 13:39:40 -050089 newselftestdir = newbuilddir + "/meta-selftest"
90
91 if os.path.exists(newbuilddir):
92 self.logger.error("Build directory %s already exists, aborting" % newbuilddir)
93 sys.exit(1)
94
95 bb.utils.mkdirhier(newbuilddir)
96 oe.path.copytree(builddir + "/conf", newbuilddir + "/conf")
97 oe.path.copytree(builddir + "/cache", newbuilddir + "/cache")
98 oe.path.copytree(selftestdir, newselftestdir)
99
100 for e in os.environ:
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500101 if builddir + "/" in os.environ[e]:
102 os.environ[e] = os.environ[e].replace(builddir + "/", newbuilddir + "/")
103 if os.environ[e].endswith(builddir):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500104 os.environ[e] = os.environ[e].replace(builddir, newbuilddir)
105
106 subprocess.check_output("git init; git add *; git commit -a -m 'initial'", cwd=newselftestdir, shell=True)
107
108 # Tried to used bitbake-layers add/remove but it requires recipe parsing and hence is too slow
109 subprocess.check_output("sed %s/conf/bblayers.conf -i -e 's#%s#%s#g'" % (newbuilddir, selftestdir, newselftestdir), cwd=newbuilddir, shell=True)
110
111 os.chdir(newbuilddir)
112
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500113 def patch_test(t):
Andrew Geissler82c905d2020-04-13 13:39:40 -0500114 if not hasattr(t, "tc"):
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500115 return
Andrew Geissler82c905d2020-04-13 13:39:40 -0500116 cp = t.tc.config_paths
117 for p in cp:
118 if selftestdir in cp[p] and newselftestdir not in cp[p]:
119 cp[p] = cp[p].replace(selftestdir, newselftestdir)
120 if builddir in cp[p] and newbuilddir not in cp[p]:
121 cp[p] = cp[p].replace(builddir, newbuilddir)
122
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500123 def patch_suite(s):
124 for x in s:
125 if isinstance(x, unittest.TestSuite):
126 patch_suite(x)
127 else:
128 patch_test(x)
129
130 patch_suite(suite)
131
Andrew Geissler82c905d2020-04-13 13:39:40 -0500132 return (builddir, newbuilddir)
133
134 def prepareSuite(self, suites, processes):
135 if processes:
136 from oeqa.core.utils.concurrencytest import ConcurrentTestSuite
137
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600138 return ConcurrentTestSuite(suites, processes, self.setup_builddir, self.removebuilddir)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500139 else:
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600140 return NonConcurrentTestSuite(suites, processes, self.setup_builddir, self.removebuilddir)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500141
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800142 def runTests(self, processes=None, machine=None, skips=[]):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500143 if machine:
144 self.custommachine = machine
145 if machine == 'random':
146 self.custommachine = choice(self.machines)
147 self.logger.info('Run tests with custom MACHINE set to: %s' % \
148 self.custommachine)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800149 return super(OESelftestTestContext, self).runTests(processes, skips)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500150
151 def listTests(self, display_type, machine=None):
152 return super(OESelftestTestContext, self).listTests(display_type)
153
154class OESelftestTestContextExecutor(OETestContextExecutor):
155 _context_class = OESelftestTestContext
156 _script_executor = 'oe-selftest'
157
158 name = 'oe-selftest'
159 help = 'oe-selftest test component'
160 description = 'Executes selftest tests'
161
162 def register_commands(self, logger, parser):
163 group = parser.add_mutually_exclusive_group(required=True)
164
165 group.add_argument('-a', '--run-all-tests', default=False,
166 action="store_true", dest="run_all_tests",
167 help='Run all (unhidden) tests')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500168 group.add_argument('-r', '--run-tests', required=False, action='store',
169 nargs='+', dest="run_tests", default=None,
170 help='Select what tests to run (modules, classes or test methods). Format should be: <module>.<class>.<test_method>')
171
172 group.add_argument('-m', '--list-modules', required=False,
173 action="store_true", default=False,
174 help='List all available test modules.')
175 group.add_argument('--list-classes', required=False,
176 action="store_true", default=False,
177 help='List all available test classes.')
178 group.add_argument('-l', '--list-tests', required=False,
179 action="store_true", default=False,
180 help='List all available tests.')
181
Andrew Geissler517393d2023-01-13 08:55:19 -0600182 parser.add_argument('-R', '--skip-tests', required=False, action='store',
183 nargs='+', dest="skips", default=None,
184 help='Skip the tests specified. Format should be <module>[.<class>[.<test_method>]]')
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800185 parser.add_argument('-j', '--num-processes', dest='processes', action='store',
186 type=int, help="number of processes to execute in parallel with")
187
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500188 parser.add_argument('--machine', required=False, choices=['random', 'all'],
189 help='Run tests on different machines (random/all).')
Brad Bishop79641f22019-09-10 07:20:22 -0400190
Brad Bishopacc069e2019-09-13 06:48:36 -0400191 parser.add_argument('-t', '--select-tag', dest="select_tags",
192 action='append', default=None,
193 help='Filter all (unhidden) tests to any that match any of the specified tag(s).')
194 parser.add_argument('-T', '--exclude-tag', dest="exclude_tags",
195 action='append', default=None,
196 help='Exclude all (unhidden) tests that match any of the specified tag(s). (exclude applies before select)')
Brad Bishop79641f22019-09-10 07:20:22 -0400197
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600198 parser.add_argument('-K', '--keep-builddir', action='store_true',
199 help='Keep the test build directory even if all tests pass')
200
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500201 parser.add_argument('-B', '--newbuilddir', help='New build directory to use for tests.')
202 parser.add_argument('-v', '--verbose', action='store_true')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500203 parser.set_defaults(func=self.run)
204
205 def _get_available_machines(self):
206 machines = []
207
208 bbpath = self.tc_kwargs['init']['td']['BBPATH'].split(':')
209
210 for path in bbpath:
211 found_machines = glob.glob(os.path.join(path, 'conf', 'machine', '*.conf'))
212 if found_machines:
213 for i in found_machines:
214 # eg: '/home/<user>/poky/meta-intel/conf/machine/intel-core2-32.conf'
215 machines.append(os.path.splitext(os.path.basename(i))[0])
216
217 return machines
218
219 def _get_cases_paths(self, bbpath):
220 cases_paths = []
221 for layer in bbpath:
222 cases_dir = os.path.join(layer, 'lib', 'oeqa', 'selftest', 'cases')
223 if os.path.isdir(cases_dir):
224 cases_paths.append(cases_dir)
225 return cases_paths
226
227 def _process_args(self, logger, args):
Brad Bishopf86d0552018-12-04 14:18:15 -0800228 args.test_start_time = time.strftime("%Y%m%d%H%M%S")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500229 args.test_data_file = None
230 args.CASES_PATHS = None
231
Brad Bishopf86d0552018-12-04 14:18:15 -0800232 bbvars = get_bb_vars()
233 logdir = os.environ.get("BUILDDIR")
234 if 'LOG_DIR' in bbvars:
235 logdir = bbvars['LOG_DIR']
Brad Bishop19323692019-04-05 15:28:33 -0400236 bb.utils.mkdirhier(logdir)
Brad Bishopf86d0552018-12-04 14:18:15 -0800237 args.output_log = logdir + '/%s-results-%s.log' % (self.name, args.test_start_time)
238
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500239 super(OESelftestTestContextExecutor, self)._process_args(logger, args)
240
241 if args.list_modules:
242 args.list_tests = 'module'
243 elif args.list_classes:
244 args.list_tests = 'class'
245 elif args.list_tests:
246 args.list_tests = 'name'
247
Brad Bishopf86d0552018-12-04 14:18:15 -0800248 self.tc_kwargs['init']['td'] = bbvars
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500249 self.tc_kwargs['init']['machines'] = self._get_available_machines()
250
251 builddir = os.environ.get("BUILDDIR")
252 self.tc_kwargs['init']['config_paths'] = {}
Andrew Geissler82c905d2020-04-13 13:39:40 -0500253 self.tc_kwargs['init']['config_paths']['testlayer_path'] = get_test_layer()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500254 self.tc_kwargs['init']['config_paths']['builddir'] = builddir
Andrew Geissler82c905d2020-04-13 13:39:40 -0500255 self.tc_kwargs['init']['config_paths']['localconf'] = os.path.join(builddir, "conf/local.conf")
256 self.tc_kwargs['init']['config_paths']['bblayers'] = os.path.join(builddir, "conf/bblayers.conf")
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500257 self.tc_kwargs['init']['newbuilddir'] = args.newbuilddir
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600258 self.tc_kwargs['init']['keep_builddir'] = args.keep_builddir
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500259
Brad Bishop79641f22019-09-10 07:20:22 -0400260 def tag_filter(tags):
261 if args.exclude_tags:
262 if any(tag in args.exclude_tags for tag in tags):
263 return True
264 if args.select_tags:
265 if not tags or not any(tag in args.select_tags for tag in tags):
266 return True
267 return False
268
269 if args.select_tags or args.exclude_tags:
270 self.tc_kwargs['load']['tags_filter'] = tag_filter
271
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500272 self.tc_kwargs['run']['skips'] = args.skips
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800273 self.tc_kwargs['run']['processes'] = args.processes
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500274
275 def _pre_run(self):
276 def _check_required_env_variables(vars):
277 for var in vars:
278 if not os.environ.get(var):
279 self.tc.logger.error("%s is not set. Did you forget to source your build environment setup script?" % var)
280 raise OEQAPreRun
281
282 def _check_presence_meta_selftest():
283 builddir = os.environ.get("BUILDDIR")
284 if os.getcwd() != builddir:
285 self.tc.logger.info("Changing cwd to %s" % builddir)
286 os.chdir(builddir)
287
288 if not "meta-selftest" in self.tc.td["BBLAYERS"]:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800289 self.tc.logger.warning("meta-selftest layer not found in BBLAYERS, adding it")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500290 meta_selftestdir = os.path.join(
291 self.tc.td["BBLAYERS_FETCH_DIR"], 'meta-selftest')
292 if os.path.isdir(meta_selftestdir):
293 runCmd("bitbake-layers add-layer %s" %meta_selftestdir)
294 # reload data is needed because a meta-selftest layer was add
295 self.tc.td = get_bb_vars()
296 self.tc.config_paths['testlayer_path'] = get_test_layer()
297 else:
298 self.tc.logger.error("could not locate meta-selftest in:\n%s" % meta_selftestdir)
299 raise OEQAPreRun
300
301 def _add_layer_libs():
302 bbpath = self.tc.td['BBPATH'].split(':')
303 layer_libdirs = [p for p in (os.path.join(l, 'lib') \
304 for l in bbpath) if os.path.exists(p)]
305 if layer_libdirs:
306 self.tc.logger.info("Adding layer libraries:")
307 for l in layer_libdirs:
308 self.tc.logger.info("\t%s" % l)
309
310 sys.path.extend(layer_libdirs)
Brad Bishopf86d0552018-12-04 14:18:15 -0800311 importlib.reload(oeqa.selftest)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500312
313 _check_required_env_variables(["BUILDDIR"])
314 _check_presence_meta_selftest()
315
316 if "buildhistory.bbclass" in self.tc.td["BBINCLUDED"]:
317 self.tc.logger.error("You have buildhistory enabled already and this isn't recommended for selftest, please disable it first.")
318 raise OEQAPreRun
319
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800320 if "rm_work.bbclass" in self.tc.td["BBINCLUDED"]:
321 self.tc.logger.error("You have rm_work enabled which isn't recommended while running oe-selftest. Please disable it before continuing.")
322 raise OEQAPreRun
323
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500324 if "PRSERV_HOST" in self.tc.td:
325 self.tc.logger.error("Please unset PRSERV_HOST in order to run oe-selftest")
326 raise OEQAPreRun
327
328 if "SANITY_TESTED_DISTROS" in self.tc.td:
329 self.tc.logger.error("Please unset SANITY_TESTED_DISTROS in order to run oe-selftest")
330 raise OEQAPreRun
331
332 _add_layer_libs()
333
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800334 self.tc.logger.info("Running bitbake -e to test the configuration is valid/parsable")
335 runCmd("bitbake -e")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500336
Brad Bishopf86d0552018-12-04 14:18:15 -0800337 def get_json_result_dir(self, args):
338 json_result_dir = os.path.join(self.tc.td["LOG_DIR"], 'oeqa')
339 if "OEQA_JSON_RESULT_DIR" in self.tc.td:
340 json_result_dir = self.tc.td["OEQA_JSON_RESULT_DIR"]
341
342 return json_result_dir
343
344 def get_configuration(self, args):
345 import platform
346 from oeqa.utils.metadata import metadata_from_bb
347 metadata = metadata_from_bb()
Andrew Geissler6aa7eec2023-03-03 12:41:14 -0600348 oeselftest_metadata = get_oeselftest_metadata(args)
Brad Bishopf86d0552018-12-04 14:18:15 -0800349 configuration = {'TEST_TYPE': 'oeselftest',
350 'STARTTIME': args.test_start_time,
351 'MACHINE': self.tc.td["MACHINE"],
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800352 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'),
Brad Bishopf86d0552018-12-04 14:18:15 -0800353 'HOST_NAME': metadata['hostname'],
Andrew Geissler6aa7eec2023-03-03 12:41:14 -0600354 'LAYERS': metadata['layers'],
355 'OESELFTEST_METADATA': oeselftest_metadata}
Brad Bishopf86d0552018-12-04 14:18:15 -0800356 return configuration
357
358 def get_result_id(self, configuration):
359 return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['HOST_DISTRO'], configuration['MACHINE'], configuration['STARTTIME'])
360
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500361 def _internal_run(self, logger, args):
362 self.module_paths = self._get_cases_paths(
363 self.tc_kwargs['init']['td']['BBPATH'].split(':'))
364
365 self.tc = self._context_class(**self.tc_kwargs['init'])
366 try:
367 self.tc.loadTests(self.module_paths, **self.tc_kwargs['load'])
368 except OEQATestNotFound as ex:
369 logger.error(ex)
370 sys.exit(1)
371
372 if args.list_tests:
373 rc = self.tc.listTests(args.list_tests, **self.tc_kwargs['list'])
374 else:
375 self._pre_run()
376 rc = self.tc.runTests(**self.tc_kwargs['run'])
Brad Bishopf86d0552018-12-04 14:18:15 -0800377 configuration = self.get_configuration(args)
378 rc.logDetails(self.get_json_result_dir(args),
379 configuration,
380 self.get_result_id(configuration))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500381 rc.logSummary(self.name)
382
383 return rc
384
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500385 def run(self, logger, args):
386 self._process_args(logger, args)
387
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500388 rc = None
389 try:
390 if args.machine:
391 logger.info('Custom machine mode enabled. MACHINE set to %s' %
392 args.machine)
393
394 if args.machine == 'all':
395 results = []
396 for m in self.tc_kwargs['init']['machines']:
397 self.tc_kwargs['run']['machine'] = m
398 results.append(self._internal_run(logger, args))
399
400 # XXX: the oe-selftest script only needs to know if one
401 # machine run fails
402 for r in results:
403 rc = r
404 if not r.wasSuccessful():
405 break
406
407 else:
408 self.tc_kwargs['run']['machine'] = args.machine
409 return self._internal_run(logger, args)
410
411 else:
412 self.tc_kwargs['run']['machine'] = args.machine
413 rc = self._internal_run(logger, args)
414 finally:
415 config_paths = self.tc_kwargs['init']['config_paths']
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500416
417 output_link = os.path.join(os.path.dirname(args.output_log),
418 "%s-results.log" % self.name)
Brad Bishopf86d0552018-12-04 14:18:15 -0800419 if os.path.lexists(output_link):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500420 os.remove(output_link)
421 os.symlink(args.output_log, output_link)
422
423 return rc
424
425_executor_class = OESelftestTestContextExecutor