blob: 494e9dbd1ec8f569f35e7407bb6c996a636c10e8 [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
25class OESelftestTestContext(OETestContext):
Andrew Geissler4ed12e12020-06-05 18:00:41 -050026 def __init__(self, td=None, logger=None, machines=None, config_paths=None, newbuilddir=None):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050027 super(OESelftestTestContext, self).__init__(td, logger)
28
29 self.machines = machines
30 self.custommachine = None
31 self.config_paths = config_paths
Andrew Geissler4ed12e12020-06-05 18:00:41 -050032 self.newbuilddir = newbuilddir
Brad Bishopd7bf8c12018-02-25 22:55:05 -050033
Andrew Geissler82c905d2020-04-13 13:39:40 -050034 def setup_builddir(self, suffix, selftestdir, suite):
35 builddir = os.environ['BUILDDIR']
36 if not selftestdir:
37 selftestdir = get_test_layer()
Andrew Geissler4ed12e12020-06-05 18:00:41 -050038 if self.newbuilddir:
39 newbuilddir = os.path.join(self.newbuilddir, 'build' + suffix)
40 else:
41 newbuilddir = builddir + suffix
Andrew Geissler82c905d2020-04-13 13:39:40 -050042 newselftestdir = newbuilddir + "/meta-selftest"
43
44 if os.path.exists(newbuilddir):
45 self.logger.error("Build directory %s already exists, aborting" % newbuilddir)
46 sys.exit(1)
47
48 bb.utils.mkdirhier(newbuilddir)
49 oe.path.copytree(builddir + "/conf", newbuilddir + "/conf")
50 oe.path.copytree(builddir + "/cache", newbuilddir + "/cache")
51 oe.path.copytree(selftestdir, newselftestdir)
52
53 for e in os.environ:
54 if builddir + "/" in os.environ[e] or os.environ[e].endswith(builddir):
55 os.environ[e] = os.environ[e].replace(builddir, newbuilddir)
56
57 subprocess.check_output("git init; git add *; git commit -a -m 'initial'", cwd=newselftestdir, shell=True)
58
59 # Tried to used bitbake-layers add/remove but it requires recipe parsing and hence is too slow
60 subprocess.check_output("sed %s/conf/bblayers.conf -i -e 's#%s#%s#g'" % (newbuilddir, selftestdir, newselftestdir), cwd=newbuilddir, shell=True)
61
62 os.chdir(newbuilddir)
63
Andrew Geissler4ed12e12020-06-05 18:00:41 -050064 def patch_test(t):
Andrew Geissler82c905d2020-04-13 13:39:40 -050065 if not hasattr(t, "tc"):
Andrew Geissler4ed12e12020-06-05 18:00:41 -050066 return
Andrew Geissler82c905d2020-04-13 13:39:40 -050067 cp = t.tc.config_paths
68 for p in cp:
69 if selftestdir in cp[p] and newselftestdir not in cp[p]:
70 cp[p] = cp[p].replace(selftestdir, newselftestdir)
71 if builddir in cp[p] and newbuilddir not in cp[p]:
72 cp[p] = cp[p].replace(builddir, newbuilddir)
73
Andrew Geissler4ed12e12020-06-05 18:00:41 -050074 def patch_suite(s):
75 for x in s:
76 if isinstance(x, unittest.TestSuite):
77 patch_suite(x)
78 else:
79 patch_test(x)
80
81 patch_suite(suite)
82
Andrew Geissler82c905d2020-04-13 13:39:40 -050083 return (builddir, newbuilddir)
84
85 def prepareSuite(self, suites, processes):
86 if processes:
87 from oeqa.core.utils.concurrencytest import ConcurrentTestSuite
88
89 return ConcurrentTestSuite(suites, processes, self.setup_builddir)
90 else:
91 self.setup_builddir("-st", None, suites)
92 return suites
93
Brad Bishop1a4b7ee2018-12-16 17:11:34 -080094 def runTests(self, processes=None, machine=None, skips=[]):
Brad Bishopd7bf8c12018-02-25 22:55:05 -050095 if machine:
96 self.custommachine = machine
97 if machine == 'random':
98 self.custommachine = choice(self.machines)
99 self.logger.info('Run tests with custom MACHINE set to: %s' % \
100 self.custommachine)
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800101 return super(OESelftestTestContext, self).runTests(processes, skips)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500102
103 def listTests(self, display_type, machine=None):
104 return super(OESelftestTestContext, self).listTests(display_type)
105
106class OESelftestTestContextExecutor(OETestContextExecutor):
107 _context_class = OESelftestTestContext
108 _script_executor = 'oe-selftest'
109
110 name = 'oe-selftest'
111 help = 'oe-selftest test component'
112 description = 'Executes selftest tests'
113
114 def register_commands(self, logger, parser):
115 group = parser.add_mutually_exclusive_group(required=True)
116
117 group.add_argument('-a', '--run-all-tests', default=False,
118 action="store_true", dest="run_all_tests",
119 help='Run all (unhidden) tests')
120 group.add_argument('-R', '--skip-tests', required=False, action='store',
121 nargs='+', dest="skips", default=None,
122 help='Run all (unhidden) tests except the ones specified. Format should be <module>[.<class>[.<test_method>]]')
123 group.add_argument('-r', '--run-tests', required=False, action='store',
124 nargs='+', dest="run_tests", default=None,
125 help='Select what tests to run (modules, classes or test methods). Format should be: <module>.<class>.<test_method>')
126
127 group.add_argument('-m', '--list-modules', required=False,
128 action="store_true", default=False,
129 help='List all available test modules.')
130 group.add_argument('--list-classes', required=False,
131 action="store_true", default=False,
132 help='List all available test classes.')
133 group.add_argument('-l', '--list-tests', required=False,
134 action="store_true", default=False,
135 help='List all available tests.')
136
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800137 parser.add_argument('-j', '--num-processes', dest='processes', action='store',
138 type=int, help="number of processes to execute in parallel with")
139
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500140 parser.add_argument('--machine', required=False, choices=['random', 'all'],
141 help='Run tests on different machines (random/all).')
Brad Bishop79641f22019-09-10 07:20:22 -0400142
Brad Bishopacc069e2019-09-13 06:48:36 -0400143 parser.add_argument('-t', '--select-tag', dest="select_tags",
144 action='append', default=None,
145 help='Filter all (unhidden) tests to any that match any of the specified tag(s).')
146 parser.add_argument('-T', '--exclude-tag', dest="exclude_tags",
147 action='append', default=None,
148 help='Exclude all (unhidden) tests that match any of the specified tag(s). (exclude applies before select)')
Brad Bishop79641f22019-09-10 07:20:22 -0400149
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500150 parser.add_argument('-B', '--newbuilddir', help='New build directory to use for tests.')
151 parser.add_argument('-v', '--verbose', action='store_true')
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500152 parser.set_defaults(func=self.run)
153
154 def _get_available_machines(self):
155 machines = []
156
157 bbpath = self.tc_kwargs['init']['td']['BBPATH'].split(':')
158
159 for path in bbpath:
160 found_machines = glob.glob(os.path.join(path, 'conf', 'machine', '*.conf'))
161 if found_machines:
162 for i in found_machines:
163 # eg: '/home/<user>/poky/meta-intel/conf/machine/intel-core2-32.conf'
164 machines.append(os.path.splitext(os.path.basename(i))[0])
165
166 return machines
167
168 def _get_cases_paths(self, bbpath):
169 cases_paths = []
170 for layer in bbpath:
171 cases_dir = os.path.join(layer, 'lib', 'oeqa', 'selftest', 'cases')
172 if os.path.isdir(cases_dir):
173 cases_paths.append(cases_dir)
174 return cases_paths
175
176 def _process_args(self, logger, args):
Brad Bishopf86d0552018-12-04 14:18:15 -0800177 args.test_start_time = time.strftime("%Y%m%d%H%M%S")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500178 args.test_data_file = None
179 args.CASES_PATHS = None
180
Brad Bishopf86d0552018-12-04 14:18:15 -0800181 bbvars = get_bb_vars()
182 logdir = os.environ.get("BUILDDIR")
183 if 'LOG_DIR' in bbvars:
184 logdir = bbvars['LOG_DIR']
Brad Bishop19323692019-04-05 15:28:33 -0400185 bb.utils.mkdirhier(logdir)
Brad Bishopf86d0552018-12-04 14:18:15 -0800186 args.output_log = logdir + '/%s-results-%s.log' % (self.name, args.test_start_time)
187
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500188 super(OESelftestTestContextExecutor, self)._process_args(logger, args)
189
190 if args.list_modules:
191 args.list_tests = 'module'
192 elif args.list_classes:
193 args.list_tests = 'class'
194 elif args.list_tests:
195 args.list_tests = 'name'
196
Brad Bishopf86d0552018-12-04 14:18:15 -0800197 self.tc_kwargs['init']['td'] = bbvars
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500198 self.tc_kwargs['init']['machines'] = self._get_available_machines()
199
200 builddir = os.environ.get("BUILDDIR")
201 self.tc_kwargs['init']['config_paths'] = {}
Andrew Geissler82c905d2020-04-13 13:39:40 -0500202 self.tc_kwargs['init']['config_paths']['testlayer_path'] = get_test_layer()
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500203 self.tc_kwargs['init']['config_paths']['builddir'] = builddir
Andrew Geissler82c905d2020-04-13 13:39:40 -0500204 self.tc_kwargs['init']['config_paths']['localconf'] = os.path.join(builddir, "conf/local.conf")
205 self.tc_kwargs['init']['config_paths']['bblayers'] = os.path.join(builddir, "conf/bblayers.conf")
Andrew Geissler4ed12e12020-06-05 18:00:41 -0500206 self.tc_kwargs['init']['newbuilddir'] = args.newbuilddir
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500207
Brad Bishop79641f22019-09-10 07:20:22 -0400208 def tag_filter(tags):
209 if args.exclude_tags:
210 if any(tag in args.exclude_tags for tag in tags):
211 return True
212 if args.select_tags:
213 if not tags or not any(tag in args.select_tags for tag in tags):
214 return True
215 return False
216
217 if args.select_tags or args.exclude_tags:
218 self.tc_kwargs['load']['tags_filter'] = tag_filter
219
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500220 self.tc_kwargs['run']['skips'] = args.skips
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800221 self.tc_kwargs['run']['processes'] = args.processes
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500222
223 def _pre_run(self):
224 def _check_required_env_variables(vars):
225 for var in vars:
226 if not os.environ.get(var):
227 self.tc.logger.error("%s is not set. Did you forget to source your build environment setup script?" % var)
228 raise OEQAPreRun
229
230 def _check_presence_meta_selftest():
231 builddir = os.environ.get("BUILDDIR")
232 if os.getcwd() != builddir:
233 self.tc.logger.info("Changing cwd to %s" % builddir)
234 os.chdir(builddir)
235
236 if not "meta-selftest" in self.tc.td["BBLAYERS"]:
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800237 self.tc.logger.warning("meta-selftest layer not found in BBLAYERS, adding it")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500238 meta_selftestdir = os.path.join(
239 self.tc.td["BBLAYERS_FETCH_DIR"], 'meta-selftest')
240 if os.path.isdir(meta_selftestdir):
241 runCmd("bitbake-layers add-layer %s" %meta_selftestdir)
242 # reload data is needed because a meta-selftest layer was add
243 self.tc.td = get_bb_vars()
244 self.tc.config_paths['testlayer_path'] = get_test_layer()
245 else:
246 self.tc.logger.error("could not locate meta-selftest in:\n%s" % meta_selftestdir)
247 raise OEQAPreRun
248
249 def _add_layer_libs():
250 bbpath = self.tc.td['BBPATH'].split(':')
251 layer_libdirs = [p for p in (os.path.join(l, 'lib') \
252 for l in bbpath) if os.path.exists(p)]
253 if layer_libdirs:
254 self.tc.logger.info("Adding layer libraries:")
255 for l in layer_libdirs:
256 self.tc.logger.info("\t%s" % l)
257
258 sys.path.extend(layer_libdirs)
Brad Bishopf86d0552018-12-04 14:18:15 -0800259 importlib.reload(oeqa.selftest)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500260
261 _check_required_env_variables(["BUILDDIR"])
262 _check_presence_meta_selftest()
263
264 if "buildhistory.bbclass" in self.tc.td["BBINCLUDED"]:
265 self.tc.logger.error("You have buildhistory enabled already and this isn't recommended for selftest, please disable it first.")
266 raise OEQAPreRun
267
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800268 if "rm_work.bbclass" in self.tc.td["BBINCLUDED"]:
269 self.tc.logger.error("You have rm_work enabled which isn't recommended while running oe-selftest. Please disable it before continuing.")
270 raise OEQAPreRun
271
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500272 if "PRSERV_HOST" in self.tc.td:
273 self.tc.logger.error("Please unset PRSERV_HOST in order to run oe-selftest")
274 raise OEQAPreRun
275
276 if "SANITY_TESTED_DISTROS" in self.tc.td:
277 self.tc.logger.error("Please unset SANITY_TESTED_DISTROS in order to run oe-selftest")
278 raise OEQAPreRun
279
280 _add_layer_libs()
281
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800282 self.tc.logger.info("Running bitbake -e to test the configuration is valid/parsable")
283 runCmd("bitbake -e")
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500284
Brad Bishopf86d0552018-12-04 14:18:15 -0800285 def get_json_result_dir(self, args):
286 json_result_dir = os.path.join(self.tc.td["LOG_DIR"], 'oeqa')
287 if "OEQA_JSON_RESULT_DIR" in self.tc.td:
288 json_result_dir = self.tc.td["OEQA_JSON_RESULT_DIR"]
289
290 return json_result_dir
291
292 def get_configuration(self, args):
293 import platform
294 from oeqa.utils.metadata import metadata_from_bb
295 metadata = metadata_from_bb()
296 configuration = {'TEST_TYPE': 'oeselftest',
297 'STARTTIME': args.test_start_time,
298 'MACHINE': self.tc.td["MACHINE"],
Brad Bishop1a4b7ee2018-12-16 17:11:34 -0800299 'HOST_DISTRO': oe.lsb.distro_identifier().replace(' ', '-'),
Brad Bishopf86d0552018-12-04 14:18:15 -0800300 'HOST_NAME': metadata['hostname'],
301 'LAYERS': metadata['layers']}
302 return configuration
303
304 def get_result_id(self, configuration):
305 return '%s_%s_%s_%s' % (configuration['TEST_TYPE'], configuration['HOST_DISTRO'], configuration['MACHINE'], configuration['STARTTIME'])
306
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500307 def _internal_run(self, logger, args):
308 self.module_paths = self._get_cases_paths(
309 self.tc_kwargs['init']['td']['BBPATH'].split(':'))
310
311 self.tc = self._context_class(**self.tc_kwargs['init'])
312 try:
313 self.tc.loadTests(self.module_paths, **self.tc_kwargs['load'])
314 except OEQATestNotFound as ex:
315 logger.error(ex)
316 sys.exit(1)
317
318 if args.list_tests:
319 rc = self.tc.listTests(args.list_tests, **self.tc_kwargs['list'])
320 else:
321 self._pre_run()
322 rc = self.tc.runTests(**self.tc_kwargs['run'])
Brad Bishopf86d0552018-12-04 14:18:15 -0800323 configuration = self.get_configuration(args)
324 rc.logDetails(self.get_json_result_dir(args),
325 configuration,
326 self.get_result_id(configuration))
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500327 rc.logSummary(self.name)
328
329 return rc
330
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500331 def run(self, logger, args):
332 self._process_args(logger, args)
333
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500334 rc = None
335 try:
336 if args.machine:
337 logger.info('Custom machine mode enabled. MACHINE set to %s' %
338 args.machine)
339
340 if args.machine == 'all':
341 results = []
342 for m in self.tc_kwargs['init']['machines']:
343 self.tc_kwargs['run']['machine'] = m
344 results.append(self._internal_run(logger, args))
345
346 # XXX: the oe-selftest script only needs to know if one
347 # machine run fails
348 for r in results:
349 rc = r
350 if not r.wasSuccessful():
351 break
352
353 else:
354 self.tc_kwargs['run']['machine'] = args.machine
355 return self._internal_run(logger, args)
356
357 else:
358 self.tc_kwargs['run']['machine'] = args.machine
359 rc = self._internal_run(logger, args)
360 finally:
361 config_paths = self.tc_kwargs['init']['config_paths']
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500362
363 output_link = os.path.join(os.path.dirname(args.output_log),
364 "%s-results.log" % self.name)
Brad Bishopf86d0552018-12-04 14:18:15 -0800365 if os.path.lexists(output_link):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500366 os.remove(output_link)
367 os.symlink(args.output_log, output_link)
368
369 return rc
370
371_executor_class = OESelftestTestContextExecutor