blob: 52366b1c8de685d5899944e0cb5429d8e71fc79a [file] [log] [blame]
Patrick Williamsc0f7c042017-02-23 20:41:17 -06001#!/usr/bin/env python3
Patrick Williamsc124f4f2015-09-15 14:41:29 -05002
3# Copyright (c) 2013 Intel Corporation
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License version 2 as
7# published by the Free Software Foundation.
8#
9# This program is distributed in the hope that it will be useful,
10# but WITHOUT ANY WARRANTY; without even the implied warranty of
11# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12# GNU General Public License for more details.
13#
14# You should have received a copy of the GNU General Public License along
15# with this program; if not, write to the Free Software Foundation, Inc.,
16# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18# DESCRIPTION
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050019# This script runs tests defined in meta/lib/oeqa/selftest/
Patrick Williamsc124f4f2015-09-15 14:41:29 -050020# It's purpose is to automate the testing of different bitbake tools.
21# To use it you just need to source your build environment setup script and
22# add the meta-selftest layer to your BBLAYERS.
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050023# Call the script as: "oe-selftest -a" to run all the tests in meta/lib/oeqa/selftest/
24# Call the script as: "oe-selftest -r <module>.<Class>.<method>" to run just a single test
25# E.g: "oe-selftest -r bblayers.BitbakeLayers" will run just the BitbakeLayers class from meta/lib/oeqa/selftest/bblayers.py
Patrick Williamsc124f4f2015-09-15 14:41:29 -050026
27
28import os
29import sys
30import unittest
31import logging
32import argparse
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050033import subprocess
34import time as t
35import re
36import fnmatch
Patrick Williamsc0f7c042017-02-23 20:41:17 -060037import collections
38import imp
Patrick Williamsc124f4f2015-09-15 14:41:29 -050039
40sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '/lib')
41import scriptpath
42scriptpath.add_bitbake_lib_path()
43scriptpath.add_oe_lib_path()
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050044import argparse_oe
Patrick Williamsc124f4f2015-09-15 14:41:29 -050045
46import oeqa.selftest
47import oeqa.utils.ftools as ftools
48from oeqa.utils.commands import runCmd, get_bb_var, get_test_layer
Brad Bishop6e60e8b2018-02-01 10:27:11 -050049from oeqa.utils.metadata import metadata_from_bb, write_metadata_file
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050050from oeqa.selftest.base import oeSelfTest, get_available_machines
Patrick Williamsc124f4f2015-09-15 14:41:29 -050051
Patrick Williamsc0f7c042017-02-23 20:41:17 -060052try:
53 import xmlrunner
54 from xmlrunner.result import _XMLTestResult as TestResult
55 from xmlrunner import XMLTestRunner as _TestRunner
56except ImportError:
57 # use the base runner instead
58 from unittest import TextTestResult as TestResult
59 from unittest import TextTestRunner as _TestRunner
60
61log_prefix = "oe-selftest-" + t.strftime("%Y%m%d-%H%M%S")
62
Patrick Williamsc124f4f2015-09-15 14:41:29 -050063def logger_create():
Patrick Williamsc0f7c042017-02-23 20:41:17 -060064 log_file = log_prefix + ".log"
Brad Bishop6e60e8b2018-02-01 10:27:11 -050065 if os.path.lexists("oe-selftest.log"):
66 os.remove("oe-selftest.log")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050067 os.symlink(log_file, "oe-selftest.log")
68
Patrick Williamsc124f4f2015-09-15 14:41:29 -050069 log = logging.getLogger("selftest")
70 log.setLevel(logging.DEBUG)
71
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050072 fh = logging.FileHandler(filename=log_file, mode='w')
Patrick Williamsc124f4f2015-09-15 14:41:29 -050073 fh.setLevel(logging.DEBUG)
74
75 ch = logging.StreamHandler(sys.stdout)
76 ch.setLevel(logging.INFO)
77
78 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
79 fh.setFormatter(formatter)
80 ch.setFormatter(formatter)
81
82 log.addHandler(fh)
83 log.addHandler(ch)
84
85 return log
86
87log = logger_create()
88
89def get_args_parser():
Brad Bishop6e60e8b2018-02-01 10:27:11 -050090 description = "Script that runs unit tests against bitbake and other Yocto related tools. The goal is to validate tools functionality and metadata integrity. Refer to https://wiki.yoctoproject.org/wiki/Oe-selftest for more information."
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050091 parser = argparse_oe.ArgumentParser(description=description)
Patrick Williamsc124f4f2015-09-15 14:41:29 -050092 group = parser.add_mutually_exclusive_group(required=True)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050093 group.add_argument('-r', '--run-tests', required=False, action='store', nargs='*', dest="run_tests", default=None, help='Select what tests to run (modules, classes or test methods). Format should be: <module>.<class>.<test_method>')
94 group.add_argument('-a', '--run-all-tests', required=False, action="store_true", dest="run_all_tests", default=False, help='Run all (unhidden) tests')
95 group.add_argument('-m', '--list-modules', required=False, action="store_true", dest="list_modules", default=False, help='List all available test modules.')
Patrick Williamsc124f4f2015-09-15 14:41:29 -050096 group.add_argument('--list-classes', required=False, action="store_true", dest="list_allclasses", default=False, help='List all available test classes.')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -050097 parser.add_argument('--coverage', action="store_true", help="Run code coverage when testing")
98 parser.add_argument('--coverage-source', dest="coverage_source", nargs="+", help="Specifiy the directories to take coverage from")
99 parser.add_argument('--coverage-include', dest="coverage_include", nargs="+", help="Specify extra patterns to include into the coverage measurement")
100 parser.add_argument('--coverage-omit', dest="coverage_omit", nargs="+", help="Specify with extra patterns to exclude from the coverage measurement")
101 group.add_argument('--run-tests-by', required=False, dest='run_tests_by', default=False, nargs='*',
102 help='run-tests-by <name|class|module|id|tag> <list of tests|classes|modules|ids|tags>')
103 group.add_argument('--list-tests-by', required=False, dest='list_tests_by', default=False, nargs='*',
104 help='list-tests-by <name|class|module|id|tag> <list of tests|classes|modules|ids|tags>')
105 group.add_argument('-l', '--list-tests', required=False, action="store_true", dest="list_tests", default=False,
106 help='List all available tests.')
107 group.add_argument('--list-tags', required=False, dest='list_tags', default=False, action="store_true",
108 help='List all tags that have been set to test cases.')
109 parser.add_argument('--machine', required=False, dest='machine', choices=['random', 'all'], default=None,
110 help='Run tests on different machines (random/all).')
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500111 parser.add_argument('--repository', required=False, dest='repository', default='', action='store',
112 help='Submit test results to a repository')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500113 return parser
114
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500115builddir = None
116
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500117
118def preflight_check():
119
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500120 global builddir
121
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500122 log.info("Checking that everything is in order before running the tests")
123
124 if not os.environ.get("BUILDDIR"):
125 log.error("BUILDDIR isn't set. Did you forget to source your build environment setup script?")
126 return False
127
128 builddir = os.environ.get("BUILDDIR")
129 if os.getcwd() != builddir:
130 log.info("Changing cwd to %s" % builddir)
131 os.chdir(builddir)
132
133 if not "meta-selftest" in get_bb_var("BBLAYERS"):
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500134 log.warn("meta-selftest layer not found in BBLAYERS, adding it")
135 meta_selftestdir = os.path.join(
136 get_bb_var("BBLAYERS_FETCH_DIR"),
137 'meta-selftest')
138 if os.path.isdir(meta_selftestdir):
139 runCmd("bitbake-layers add-layer %s" %meta_selftestdir)
140 else:
141 log.error("could not locate meta-selftest in:\n%s"
142 %meta_selftestdir)
143 return False
144
145 if "buildhistory.bbclass" in get_bb_var("BBINCLUDED"):
146 log.error("You have buildhistory enabled already and this isn't recommended for selftest, please disable it first.")
147 return False
148
149 if get_bb_var("PRSERV_HOST"):
150 log.error("Please unset PRSERV_HOST in order to run oe-selftest")
151 return False
152
153 if get_bb_var("SANITY_TESTED_DISTROS"):
154 log.error("Please unset SANITY_TESTED_DISTROS in order to run oe-selftest")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500155 return False
156
157 log.info("Running bitbake -p")
158 runCmd("bitbake -p")
159
160 return True
161
162def add_include():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500163 global builddir
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500164 if "#include added by oe-selftest.py" \
165 not in ftools.read_file(os.path.join(builddir, "conf/local.conf")):
166 log.info("Adding: \"include selftest.inc\" in local.conf")
167 ftools.append_file(os.path.join(builddir, "conf/local.conf"), \
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500168 "\n#include added by oe-selftest.py\ninclude machine.inc\ninclude selftest.inc")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500169
170 if "#include added by oe-selftest.py" \
171 not in ftools.read_file(os.path.join(builddir, "conf/bblayers.conf")):
172 log.info("Adding: \"include bblayers.inc\" in bblayers.conf")
173 ftools.append_file(os.path.join(builddir, "conf/bblayers.conf"), \
174 "\n#include added by oe-selftest.py\ninclude bblayers.inc")
175
176def remove_include():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500177 global builddir
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500178 if builddir is None:
179 return
180 if "#include added by oe-selftest.py" \
181 in ftools.read_file(os.path.join(builddir, "conf/local.conf")):
182 log.info("Removing the include from local.conf")
183 ftools.remove_from_file(os.path.join(builddir, "conf/local.conf"), \
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500184 "\n#include added by oe-selftest.py\ninclude machine.inc\ninclude selftest.inc")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500185
186 if "#include added by oe-selftest.py" \
187 in ftools.read_file(os.path.join(builddir, "conf/bblayers.conf")):
188 log.info("Removing the include from bblayers.conf")
189 ftools.remove_from_file(os.path.join(builddir, "conf/bblayers.conf"), \
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500190 "\n#include added by oe-selftest.py\ninclude bblayers.inc")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500191
192def remove_inc_files():
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500193 global builddir
194 if builddir is None:
195 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500196 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500197 os.remove(os.path.join(builddir, "conf/selftest.inc"))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500198 for root, _, files in os.walk(get_test_layer()):
199 for f in files:
200 if f == 'test_recipe.inc':
201 os.remove(os.path.join(root, f))
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500202 except OSError as e:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500203 pass
204
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500205 for incl_file in ['conf/bblayers.inc', 'conf/machine.inc']:
206 try:
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500207 os.remove(os.path.join(builddir, incl_file))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500208 except:
209 pass
210
211
212def get_tests_modules(include_hidden=False):
213 modules_list = list()
214 for modules_path in oeqa.selftest.__path__:
215 for (p, d, f) in os.walk(modules_path):
216 files = sorted([f for f in os.listdir(p) if f.endswith('.py') and not (f.startswith('_') and not include_hidden) and not f.startswith('__') and f != 'base.py'])
217 for f in files:
218 submodules = p.split("selftest")[-1]
219 module = ""
220 if submodules:
221 module = 'oeqa.selftest' + submodules.replace("/",".") + "." + f.split('.py')[0]
222 else:
223 module = 'oeqa.selftest.' + f.split('.py')[0]
224 if module not in modules_list:
225 modules_list.append(module)
226 return modules_list
227
228
229def get_tests(exclusive_modules=[], include_hidden=False):
230 test_modules = list()
231 for x in exclusive_modules:
232 test_modules.append('oeqa.selftest.' + x)
233 if not test_modules:
234 inc_hidden = include_hidden
235 test_modules = get_tests_modules(inc_hidden)
236
237 return test_modules
238
239
240class Tc:
241 def __init__(self, tcname, tcclass, tcmodule, tcid=None, tctag=None):
242 self.tcname = tcname
243 self.tcclass = tcclass
244 self.tcmodule = tcmodule
245 self.tcid = tcid
246 # A test case can have multiple tags (as tuples) otherwise str will suffice
247 self.tctag = tctag
248 self.fullpath = '.'.join(['oeqa', 'selftest', tcmodule, tcclass, tcname])
249
250
251def get_tests_from_module(tmod):
252 tlist = []
253 prefix = 'oeqa.selftest.'
254
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500255 try:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500256 import importlib
257 modlib = importlib.import_module(tmod)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600258 for mod in list(vars(modlib).values()):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500259 if isinstance(mod, type(oeSelfTest)) and issubclass(mod, oeSelfTest) and mod is not oeSelfTest:
260 for test in dir(mod):
261 if test.startswith('test_') and hasattr(vars(mod)[test], '__call__'):
262 # Get test case id and feature tag
263 # NOTE: if testcase decorator or feature tag not set will throw error
264 try:
265 tid = vars(mod)[test].test_case
266 except:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267 print('DEBUG: tc id missing for ' + str(test))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500268 tid = None
269 try:
270 ttag = vars(mod)[test].tag__feature
271 except:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600272 # print('DEBUG: feature tag missing for ' + str(test))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500273 ttag = None
274
275 # NOTE: for some reason lstrip() doesn't work for mod.__module__
276 tlist.append(Tc(test, mod.__name__, mod.__module__.replace(prefix, ''), tid, ttag))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500277 except:
278 pass
279
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500280 return tlist
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500281
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500282
283def get_all_tests():
284 # Get all the test modules (except the hidden ones)
285 testlist = []
286 tests_modules = get_tests_modules()
287 # Get all the tests from modules
288 for tmod in sorted(tests_modules):
289 testlist += get_tests_from_module(tmod)
290 return testlist
291
292
293def get_testsuite_by(criteria, keyword):
294 # Get a testsuite based on 'keyword'
295 # criteria: name, class, module, id, tag
296 # keyword: a list of tests, classes, modules, ids, tags
297
298 ts = []
299 all_tests = get_all_tests()
300
301 def get_matches(values):
302 # Get an item and return the ones that match with keyword(s)
303 # values: the list of items (names, modules, classes...)
304 result = []
305 remaining = values[:]
306 for key in keyword:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600307 found = False
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500308 if key in remaining:
309 # Regular matching of exact item
310 result.append(key)
311 remaining.remove(key)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600312 found = True
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500313 else:
314 # Wildcard matching
315 pattern = re.compile(fnmatch.translate(r"%s" % key))
316 added = [x for x in remaining if pattern.match(x)]
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600317 if added:
318 result.extend(added)
319 remaining = [x for x in remaining if x not in added]
320 found = True
321 if not found:
322 log.error("Failed to find test: %s" % key)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500323
324 return result
325
326 if criteria == 'name':
327 names = get_matches([ tc.tcname for tc in all_tests ])
328 ts = [ tc for tc in all_tests if tc.tcname in names ]
329
330 elif criteria == 'class':
331 classes = get_matches([ tc.tcclass for tc in all_tests ])
332 ts = [ tc for tc in all_tests if tc.tcclass in classes ]
333
334 elif criteria == 'module':
335 modules = get_matches([ tc.tcmodule for tc in all_tests ])
336 ts = [ tc for tc in all_tests if tc.tcmodule in modules ]
337
338 elif criteria == 'id':
339 ids = get_matches([ str(tc.tcid) for tc in all_tests ])
340 ts = [ tc for tc in all_tests if str(tc.tcid) in ids ]
341
342 elif criteria == 'tag':
343 values = set()
344 for tc in all_tests:
345 # tc can have multiple tags (as tuple) otherwise str will suffice
346 if isinstance(tc.tctag, tuple):
347 values |= { str(tag) for tag in tc.tctag }
348 else:
349 values.add(str(tc.tctag))
350
351 tags = get_matches(list(values))
352
353 for tc in all_tests:
354 for tag in tags:
355 if isinstance(tc.tctag, tuple) and tag in tc.tctag:
356 ts.append(tc)
357 elif tag == tc.tctag:
358 ts.append(tc)
359
360 # Remove duplicates from the list
361 ts = list(set(ts))
362
363 return ts
364
365
366def list_testsuite_by(criteria, keyword):
367 # Get a testsuite based on 'keyword'
368 # criteria: name, class, module, id, tag
369 # keyword: a list of tests, classes, modules, ids, tags
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500370 def tc_key(t):
371 if t[0] is None:
372 return (0,) + t[1:]
373 return t
374 # tcid may be None if no ID was assigned, in which case sorted() will throw
375 # a TypeError as Python 3 does not allow comparison (<,<=,>=,>) of
376 # heterogeneous types, handle this by using a custom key generator
377 ts = sorted([ (tc.tcid, tc.tctag, tc.tcname, tc.tcclass, tc.tcmodule) \
378 for tc in get_testsuite_by(criteria, keyword) ], key=tc_key)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600379 print('_' * 150)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500380 for t in ts:
381 if isinstance(t[1], (tuple, list)):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600382 print('%-4s\t%-20s\t%-60s\t%-25s\t%-20s' % (t[0], ', '.join(t[1]), t[2], t[3], t[4]))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500383 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600384 print('%-4s\t%-20s\t%-60s\t%-25s\t%-20s' % t)
385 print('_' * 150)
386 print('Filtering by:\t %s' % criteria)
387 print('Looking for:\t %s' % ', '.join(str(x) for x in keyword))
388 print('Total found:\t %s' % len(ts))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500389
390
391def list_tests():
392 # List all available oe-selftest tests
393
394 ts = get_all_tests()
395
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600396 print('%-4s\t%-10s\t%-50s' % ('id', 'tag', 'test'))
397 print('_' * 80)
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500398 for t in ts:
399 if isinstance(t.tctag, (tuple, list)):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600400 print('%-4s\t%-10s\t%-50s' % (t.tcid, ', '.join(t.tctag), '.'.join([t.tcmodule, t.tcclass, t.tcname])))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500401 else:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600402 print('%-4s\t%-10s\t%-50s' % (t.tcid, t.tctag, '.'.join([t.tcmodule, t.tcclass, t.tcname])))
403 print('_' * 80)
404 print('Total found:\t %s' % len(ts))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500405
406def list_tags():
407 # Get all tags set to test cases
408 # This is useful when setting tags to test cases
409 # The list of tags should be kept as minimal as possible
410 tags = set()
411 all_tests = get_all_tests()
412
413 for tc in all_tests:
414 if isinstance(tc.tctag, (tuple, list)):
415 tags.update(set(tc.tctag))
416 else:
417 tags.add(tc.tctag)
418
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600419 print('Tags:\t%s' % ', '.join(str(x) for x in tags))
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500420
421def coverage_setup(coverage_source, coverage_include, coverage_omit):
422 """ Set up the coverage measurement for the testcases to be run """
423 import datetime
424 import subprocess
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500425 global builddir
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500426 pokydir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600427 curcommit= subprocess.check_output(["git", "--git-dir", os.path.join(pokydir, ".git"), "rev-parse", "HEAD"]).decode('utf-8')
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500428 coveragerc = "%s/.coveragerc" % builddir
429 data_file = "%s/.coverage." % builddir
430 data_file += datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
431 if os.path.isfile(data_file):
432 os.remove(data_file)
433 with open(coveragerc, 'w') as cps:
434 cps.write("# Generated with command '%s'\n" % " ".join(sys.argv))
435 cps.write("# HEAD commit %s\n" % curcommit.strip())
436 cps.write("[run]\n")
437 cps.write("data_file = %s\n" % data_file)
438 cps.write("branch = True\n")
439 # Measure just BBLAYERS, scripts and bitbake folders
440 cps.write("source = \n")
441 if coverage_source:
442 for directory in coverage_source:
443 if not os.path.isdir(directory):
444 log.warn("Directory %s is not valid.", directory)
445 cps.write(" %s\n" % directory)
446 else:
447 for layer in get_bb_var('BBLAYERS').split():
448 cps.write(" %s\n" % layer)
449 cps.write(" %s\n" % os.path.dirname(os.path.realpath(__file__)))
450 cps.write(" %s\n" % os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),'bitbake'))
451
452 if coverage_include:
453 cps.write("include = \n")
454 for pattern in coverage_include:
455 cps.write(" %s\n" % pattern)
456 if coverage_omit:
457 cps.write("omit = \n")
458 for pattern in coverage_omit:
459 cps.write(" %s\n" % pattern)
460
461 return coveragerc
462
463def coverage_report():
464 """ Loads the coverage data gathered and reports it back """
465 try:
466 # Coverage4 uses coverage.Coverage
467 from coverage import Coverage
468 except:
469 # Coverage under version 4 uses coverage.coverage
470 from coverage import coverage as Coverage
471
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600472 import io as StringIO
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500473 from coverage.misc import CoverageException
474
475 cov_output = StringIO.StringIO()
476 # Creating the coverage data with the setting from the configuration file
477 cov = Coverage(config_file = os.environ.get('COVERAGE_PROCESS_START'))
478 try:
479 # Load data from the data file specified in the configuration
480 cov.load()
481 # Store report data in a StringIO variable
482 cov.report(file = cov_output, show_missing=False)
483 log.info("\n%s" % cov_output.getvalue())
484 except CoverageException as e:
485 # Show problems with the reporting. Since Coverage4 not finding any data to report raises an exception
486 log.warn("%s" % str(e))
487 finally:
488 cov_output.close()
489
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500490
491def main():
492 parser = get_args_parser()
493 args = parser.parse_args()
494
495 # Add <layer>/lib to sys.path, so layers can add selftests
496 log.info("Running bitbake -e to get BBPATH")
497 bbpath = get_bb_var('BBPATH').split(':')
498 layer_libdirs = [p for p in (os.path.join(l, 'lib') for l in bbpath) if os.path.exists(p)]
499 sys.path.extend(layer_libdirs)
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600500 imp.reload(oeqa.selftest)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500501
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500502 # act like bitbake and enforce en_US.UTF-8 locale
503 os.environ["LC_ALL"] = "en_US.UTF-8"
504
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500505 if args.run_tests_by and len(args.run_tests_by) >= 2:
506 valid_options = ['name', 'class', 'module', 'id', 'tag']
507 if args.run_tests_by[0] not in valid_options:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600508 print('--run-tests-by %s not a valid option. Choose one of <name|class|module|id|tag>.' % args.run_tests_by[0])
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500509 return 1
510 else:
511 criteria = args.run_tests_by[0]
512 keyword = args.run_tests_by[1:]
513 ts = sorted([ tc.fullpath for tc in get_testsuite_by(criteria, keyword) ])
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600514 if not ts:
515 return 1
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500516
517 if args.list_tests_by and len(args.list_tests_by) >= 2:
518 valid_options = ['name', 'class', 'module', 'id', 'tag']
519 if args.list_tests_by[0] not in valid_options:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600520 print('--list-tests-by %s not a valid option. Choose one of <name|class|module|id|tag>.' % args.list_tests_by[0])
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500521 return 1
522 else:
523 criteria = args.list_tests_by[0]
524 keyword = args.list_tests_by[1:]
525 list_testsuite_by(criteria, keyword)
526
527 if args.list_tests:
528 list_tests()
529
530 if args.list_tags:
531 list_tags()
532
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500533 if args.list_allclasses:
534 args.list_modules = True
535
536 if args.list_modules:
537 log.info('Listing all available test modules:')
538 testslist = get_tests(include_hidden=True)
539 for test in testslist:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500540 module = test.split('oeqa.selftest.')[-1]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500541 info = ''
542 if module.startswith('_'):
543 info = ' (hidden)'
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600544 print(module + info)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500545 if args.list_allclasses:
546 try:
547 import importlib
548 modlib = importlib.import_module(test)
549 for v in vars(modlib):
550 t = vars(modlib)[v]
551 if isinstance(t, type(oeSelfTest)) and issubclass(t, oeSelfTest) and t!=oeSelfTest:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600552 print(" --", v)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500553 for method in dir(t):
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600554 if method.startswith("test_") and isinstance(vars(t)[method], collections.Callable):
555 print(" -- --", method)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500556
557 except (AttributeError, ImportError) as e:
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600558 print(e)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500559 pass
560
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500561 if args.run_tests or args.run_all_tests or args.run_tests_by:
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500562 if not preflight_check():
563 return 1
564
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500565 if args.run_tests_by:
566 testslist = ts
567 else:
568 testslist = get_tests(exclusive_modules=(args.run_tests or []), include_hidden=False)
569
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500570 suite = unittest.TestSuite()
571 loader = unittest.TestLoader()
572 loader.sortTestMethodsUsing = None
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600573 runner = TestRunner(verbosity=2,
574 resultclass=buildResultClass(args))
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500575 # we need to do this here, otherwise just loading the tests
576 # will take 2 minutes (bitbake -e calls)
577 oeSelfTest.testlayer_path = get_test_layer()
578 for test in testslist:
579 log.info("Loading tests from: %s" % test)
580 try:
581 suite.addTests(loader.loadTestsFromName(test))
582 except AttributeError as e:
583 log.error("Failed to import %s" % test)
584 log.error(e)
585 return 1
586 add_include()
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500587
588 if args.machine:
589 # Custom machine sets only weak default values (??=) for MACHINE in machine.inc
590 # This let test cases that require a specific MACHINE to be able to override it, using (?= or =)
591 log.info('Custom machine mode enabled. MACHINE set to %s' % args.machine)
592 if args.machine == 'random':
593 os.environ['CUSTOMMACHINE'] = 'random'
594 result = runner.run(suite)
595 else: # all
596 machines = get_available_machines()
597 for m in machines:
598 log.info('Run tests with custom MACHINE set to: %s' % m)
599 os.environ['CUSTOMMACHINE'] = m
600 result = runner.run(suite)
601 else:
602 result = runner.run(suite)
603
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500604 log.info("Finished")
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500605
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500606 if args.repository:
607 import git
608 # Commit tests results to repository
609 metadata = metadata_from_bb()
610 git_dir = os.path.join(os.getcwd(), 'selftest')
611 if not os.path.isdir(git_dir):
612 os.mkdir(git_dir)
613
614 log.debug('Checking for git repository in %s' % git_dir)
615 try:
616 repo = git.Repo(git_dir)
617 except git.exc.InvalidGitRepositoryError:
618 log.debug("Couldn't find git repository %s; "
619 "cloning from %s" % (git_dir, args.repository))
620 repo = git.Repo.clone_from(args.repository, git_dir)
621
622 r_branches = repo.git.branch(r=True)
623 r_branches = set(r_branches.replace('origin/', '').split())
624 l_branches = {str(branch) for branch in repo.branches}
625 branch = '%s/%s/%s' % (metadata['hostname'],
626 metadata['layers']['meta'].get('branch', '(nogit)'),
627 metadata['config']['MACHINE'])
628
629 if branch in l_branches:
630 log.debug('Found branch in local repository, checking out')
631 repo.git.checkout(branch)
632 elif branch in r_branches:
633 log.debug('Found branch in remote repository, checking'
634 ' out and pulling')
635 repo.git.checkout(branch)
636 repo.git.pull()
637 else:
638 log.debug('New branch %s' % branch)
639 repo.git.checkout('master')
640 repo.git.checkout(b=branch)
641
642 cleanResultsDir(repo)
643 xml_dir = os.path.join(os.getcwd(), log_prefix)
644 copyResultFiles(xml_dir, git_dir, repo)
645 metadata_file = os.path.join(git_dir, 'metadata.xml')
646 write_metadata_file(metadata_file, metadata)
647 repo.index.add([metadata_file])
648 repo.index.write()
649
650 # Get information for commit message
651 layer_info = ''
652 for layer, values in metadata['layers'].items():
653 layer_info = '%s%-17s = %s:%s\n' % (layer_info, layer,
654 values.get('branch', '(nogit)'), values.get('commit', '0'*40))
655 msg = 'Selftest for build %s of %s for machine %s on %s\n\n%s' % (
656 log_prefix[12:], metadata['distro']['pretty_name'],
657 metadata['config']['MACHINE'], metadata['hostname'], layer_info)
658
659 log.debug('Commiting results to local repository')
660 repo.index.commit(msg)
661 if not repo.is_dirty():
662 try:
663 if branch in r_branches:
664 log.debug('Pushing changes to remote repository')
665 repo.git.push()
666 else:
667 log.debug('Pushing changes to remote repository '
668 'creating new branch')
669 repo.git.push('-u', 'origin', branch)
670 except GitCommandError:
671 log.error('Falied to push to remote repository')
672 return 1
673 else:
674 log.error('Local repository is dirty, not pushing commits')
675
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500676 if result.wasSuccessful():
677 return 0
678 else:
679 return 1
680
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500681def buildResultClass(args):
682 """Build a Result Class to use in the testcase execution"""
683 import site
684
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600685 class StampedResult(TestResult):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500686 """
687 Custom TestResult that prints the time when a test starts. As oe-selftest
688 can take a long time (ie a few hours) to run, timestamps help us understand
689 what tests are taking a long time to execute.
690 If coverage is required, this class executes the coverage setup and reporting.
691 """
692 def startTest(self, test):
693 import time
694 self.stream.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + " - ")
695 super(StampedResult, self).startTest(test)
696
697 def startTestRun(self):
698 """ Setup coverage before running any testcase """
699
700 # variable holding the coverage configuration file allowing subprocess to be measured
701 self.coveragepth = None
702
703 # indicates the system if coverage is currently installed
704 self.coverage_installed = True
705
706 if args.coverage or args.coverage_source or args.coverage_include or args.coverage_omit:
707 try:
708 # check if user can do coverage
709 import coverage
710 except:
711 log.warn("python coverage is not installed. More info on https://pypi.python.org/pypi/coverage")
712 self.coverage_installed = False
713
714 if self.coverage_installed:
715 log.info("Coverage is enabled")
716
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600717 major_version = int(coverage.version.__version__[0])
718 if major_version < 4:
719 log.error("python coverage %s installed. Require version 4 or greater." % coverage.version.__version__)
720 self.stop()
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500721 # In case the user has not set the variable COVERAGE_PROCESS_START,
722 # create a default one and export it. The COVERAGE_PROCESS_START
723 # value indicates where the coverage configuration file resides
724 # More info on https://pypi.python.org/pypi/coverage
725 if not os.environ.get('COVERAGE_PROCESS_START'):
726 os.environ['COVERAGE_PROCESS_START'] = coverage_setup(args.coverage_source, args.coverage_include, args.coverage_omit)
727
728 # Use default site.USER_SITE and write corresponding config file
729 site.ENABLE_USER_SITE = True
730 if not os.path.exists(site.USER_SITE):
731 os.makedirs(site.USER_SITE)
732 self.coveragepth = os.path.join(site.USER_SITE, "coverage.pth")
733 with open(self.coveragepth, 'w') as cps:
734 cps.write('import sys,site; sys.path.extend(site.getsitepackages()); import coverage; coverage.process_startup();')
735
736 def stopTestRun(self):
737 """ Report coverage data after the testcases are run """
738
739 if args.coverage or args.coverage_source or args.coverage_include or args.coverage_omit:
740 if self.coverage_installed:
741 with open(os.environ['COVERAGE_PROCESS_START']) as ccf:
742 log.info("Coverage configuration file (%s)" % os.environ.get('COVERAGE_PROCESS_START'))
743 log.info("===========================")
744 log.info("\n%s" % "".join(ccf.readlines()))
745
746 log.info("Coverage Report")
747 log.info("===============")
748 try:
749 coverage_report()
750 finally:
751 # remove the pth file
752 try:
753 os.remove(self.coveragepth)
754 except OSError:
755 log.warn("Expected temporal file from coverage is missing, ignoring removal.")
756
757 return StampedResult
758
Brad Bishop6e60e8b2018-02-01 10:27:11 -0500759def cleanResultsDir(repo):
760 """ Remove result files from directory """
761
762 xml_files = []
763 directory = repo.working_tree_dir
764 for f in os.listdir(directory):
765 path = os.path.join(directory, f)
766 if os.path.isfile(path) and path.endswith('.xml'):
767 xml_files.append(f)
768 repo.index.remove(xml_files, working_tree=True)
769
770def copyResultFiles(src, dst, repo):
771 """ Copy result files from src to dst removing the time stamp. """
772
773 import shutil
774
775 re_time = re.compile("-[0-9]+")
776 file_list = []
777
778 for root, subdirs, files in os.walk(src):
779 tmp_dir = root.replace(src, '').lstrip('/')
780 for s in subdirs:
781 os.mkdir(os.path.join(dst, tmp_dir, s))
782 for f in files:
783 file_name = os.path.join(dst, tmp_dir, re_time.sub("", f))
784 shutil.copy2(os.path.join(root, f), file_name)
785 file_list.append(file_name)
786 repo.index.add(file_list)
787
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600788class TestRunner(_TestRunner):
789 """Test runner class aware of exporting tests."""
790 def __init__(self, *args, **kwargs):
791 try:
792 exportdir = os.path.join(os.getcwd(), log_prefix)
793 kwargsx = dict(**kwargs)
794 # argument specific to XMLTestRunner, if adding a new runner then
795 # also add logic to use other runner's args.
796 kwargsx['output'] = exportdir
797 kwargsx['descriptions'] = False
798 # done for the case where telling the runner where to export
799 super(TestRunner, self).__init__(*args, **kwargsx)
800 except TypeError:
801 log.info("test runner init'ed like unittest")
802 super(TestRunner, self).__init__(*args, **kwargs)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500803
804if __name__ == "__main__":
805 try:
806 ret = main()
807 except Exception:
808 ret = 1
809 import traceback
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500810 traceback.print_exc()
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500811 finally:
812 remove_include()
813 remove_inc_files()
814 sys.exit(ret)