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