oe-selftest 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2013 Intel Corporation
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License version 2 as
  6. # published by the Free Software Foundation.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License along
  14. # with this program; if not, write to the Free Software Foundation, Inc.,
  15. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  16. # DESCRIPTION
  17. # This script runs tests defined in meta/lib/oeqa/selftest/
  18. # It's purpose is to automate the testing of different bitbake tools.
  19. # To use it you just need to source your build environment setup script and
  20. # add the meta-selftest layer to your BBLAYERS.
  21. # Call the script as: "oe-selftest -a" to run all the tests in meta/lib/oeqa/selftest/
  22. # Call the script as: "oe-selftest -r <module>.<Class>.<method>" to run just a single test
  23. # E.g: "oe-selftest -r bblayers.BitbakeLayers" will run just the BitbakeLayers class from meta/lib/oeqa/selftest/bblayers.py
  24. import os
  25. import sys
  26. import unittest
  27. import logging
  28. import argparse
  29. import subprocess
  30. import time as t
  31. import re
  32. import fnmatch
  33. import collections
  34. import imp
  35. sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '/lib')
  36. import scriptpath
  37. scriptpath.add_bitbake_lib_path()
  38. scriptpath.add_oe_lib_path()
  39. import argparse_oe
  40. import oeqa.selftest
  41. import oeqa.utils.ftools as ftools
  42. from oeqa.utils.commands import runCmd, get_bb_var, get_test_layer
  43. from oeqa.selftest.base import oeSelfTest, get_available_machines
  44. def logger_create():
  45. log_file = "oe-selftest-" + t.strftime("%Y-%m-%d_%H:%M:%S") + ".log"
  46. if os.path.exists("oe-selftest.log"): os.remove("oe-selftest.log")
  47. os.symlink(log_file, "oe-selftest.log")
  48. log = logging.getLogger("selftest")
  49. log.setLevel(logging.DEBUG)
  50. fh = logging.FileHandler(filename=log_file, mode='w')
  51. fh.setLevel(logging.DEBUG)
  52. ch = logging.StreamHandler(sys.stdout)
  53. ch.setLevel(logging.INFO)
  54. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  55. fh.setFormatter(formatter)
  56. ch.setFormatter(formatter)
  57. log.addHandler(fh)
  58. log.addHandler(ch)
  59. return log
  60. log = logger_create()
  61. def get_args_parser():
  62. description = "Script that runs unit tests agains 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."
  63. parser = argparse_oe.ArgumentParser(description=description)
  64. group = parser.add_mutually_exclusive_group(required=True)
  65. 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>')
  66. group.add_argument('-a', '--run-all-tests', required=False, action="store_true", dest="run_all_tests", default=False, help='Run all (unhidden) tests')
  67. group.add_argument('-m', '--list-modules', required=False, action="store_true", dest="list_modules", default=False, help='List all available test modules.')
  68. group.add_argument('--list-classes', required=False, action="store_true", dest="list_allclasses", default=False, help='List all available test classes.')
  69. parser.add_argument('--coverage', action="store_true", help="Run code coverage when testing")
  70. parser.add_argument('--coverage-source', dest="coverage_source", nargs="+", help="Specifiy the directories to take coverage from")
  71. parser.add_argument('--coverage-include', dest="coverage_include", nargs="+", help="Specify extra patterns to include into the coverage measurement")
  72. parser.add_argument('--coverage-omit', dest="coverage_omit", nargs="+", help="Specify with extra patterns to exclude from the coverage measurement")
  73. group.add_argument('--run-tests-by', required=False, dest='run_tests_by', default=False, nargs='*',
  74. help='run-tests-by <name|class|module|id|tag> <list of tests|classes|modules|ids|tags>')
  75. group.add_argument('--list-tests-by', required=False, dest='list_tests_by', default=False, nargs='*',
  76. help='list-tests-by <name|class|module|id|tag> <list of tests|classes|modules|ids|tags>')
  77. group.add_argument('-l', '--list-tests', required=False, action="store_true", dest="list_tests", default=False,
  78. help='List all available tests.')
  79. group.add_argument('--list-tags', required=False, dest='list_tags', default=False, action="store_true",
  80. help='List all tags that have been set to test cases.')
  81. parser.add_argument('--machine', required=False, dest='machine', choices=['random', 'all'], default=None,
  82. help='Run tests on different machines (random/all).')
  83. return parser
  84. def preflight_check():
  85. log.info("Checking that everything is in order before running the tests")
  86. if not os.environ.get("BUILDDIR"):
  87. log.error("BUILDDIR isn't set. Did you forget to source your build environment setup script?")
  88. return False
  89. builddir = os.environ.get("BUILDDIR")
  90. if os.getcwd() != builddir:
  91. log.info("Changing cwd to %s" % builddir)
  92. os.chdir(builddir)
  93. if not "meta-selftest" in get_bb_var("BBLAYERS"):
  94. log.error("You don't seem to have the meta-selftest layer in BBLAYERS")
  95. return False
  96. log.info("Running bitbake -p")
  97. runCmd("bitbake -p")
  98. return True
  99. def add_include():
  100. builddir = os.environ.get("BUILDDIR")
  101. if "#include added by oe-selftest.py" \
  102. not in ftools.read_file(os.path.join(builddir, "conf/local.conf")):
  103. log.info("Adding: \"include selftest.inc\" in local.conf")
  104. ftools.append_file(os.path.join(builddir, "conf/local.conf"), \
  105. "\n#include added by oe-selftest.py\ninclude machine.inc\ninclude selftest.inc")
  106. if "#include added by oe-selftest.py" \
  107. not in ftools.read_file(os.path.join(builddir, "conf/bblayers.conf")):
  108. log.info("Adding: \"include bblayers.inc\" in bblayers.conf")
  109. ftools.append_file(os.path.join(builddir, "conf/bblayers.conf"), \
  110. "\n#include added by oe-selftest.py\ninclude bblayers.inc")
  111. def remove_include():
  112. builddir = os.environ.get("BUILDDIR")
  113. if builddir is None:
  114. return
  115. if "#include added by oe-selftest.py" \
  116. in ftools.read_file(os.path.join(builddir, "conf/local.conf")):
  117. log.info("Removing the include from local.conf")
  118. ftools.remove_from_file(os.path.join(builddir, "conf/local.conf"), \
  119. "\n#include added by oe-selftest.py\ninclude machine.inc\ninclude selftest.inc")
  120. if "#include added by oe-selftest.py" \
  121. in ftools.read_file(os.path.join(builddir, "conf/bblayers.conf")):
  122. log.info("Removing the include from bblayers.conf")
  123. ftools.remove_from_file(os.path.join(builddir, "conf/bblayers.conf"), \
  124. "\n#include added by oe-selftest.py\ninclude bblayers.inc")
  125. def remove_inc_files():
  126. try:
  127. os.remove(os.path.join(os.environ.get("BUILDDIR"), "conf/selftest.inc"))
  128. for root, _, files in os.walk(get_test_layer()):
  129. for f in files:
  130. if f == 'test_recipe.inc':
  131. os.remove(os.path.join(root, f))
  132. except (AttributeError, OSError,) as e: # AttributeError may happen if BUILDDIR is not set
  133. pass
  134. for incl_file in ['conf/bblayers.inc', 'conf/machine.inc']:
  135. try:
  136. os.remove(os.path.join(os.environ.get("BUILDDIR"), incl_file))
  137. except:
  138. pass
  139. def get_tests_modules(include_hidden=False):
  140. modules_list = list()
  141. for modules_path in oeqa.selftest.__path__:
  142. for (p, d, f) in os.walk(modules_path):
  143. 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'])
  144. for f in files:
  145. submodules = p.split("selftest")[-1]
  146. module = ""
  147. if submodules:
  148. module = 'oeqa.selftest' + submodules.replace("/",".") + "." + f.split('.py')[0]
  149. else:
  150. module = 'oeqa.selftest.' + f.split('.py')[0]
  151. if module not in modules_list:
  152. modules_list.append(module)
  153. return modules_list
  154. def get_tests(exclusive_modules=[], include_hidden=False):
  155. test_modules = list()
  156. for x in exclusive_modules:
  157. test_modules.append('oeqa.selftest.' + x)
  158. if not test_modules:
  159. inc_hidden = include_hidden
  160. test_modules = get_tests_modules(inc_hidden)
  161. return test_modules
  162. class Tc:
  163. def __init__(self, tcname, tcclass, tcmodule, tcid=None, tctag=None):
  164. self.tcname = tcname
  165. self.tcclass = tcclass
  166. self.tcmodule = tcmodule
  167. self.tcid = tcid
  168. # A test case can have multiple tags (as tuples) otherwise str will suffice
  169. self.tctag = tctag
  170. self.fullpath = '.'.join(['oeqa', 'selftest', tcmodule, tcclass, tcname])
  171. def get_tests_from_module(tmod):
  172. tlist = []
  173. prefix = 'oeqa.selftest.'
  174. try:
  175. import importlib
  176. modlib = importlib.import_module(tmod)
  177. for mod in list(vars(modlib).values()):
  178. if isinstance(mod, type(oeSelfTest)) and issubclass(mod, oeSelfTest) and mod is not oeSelfTest:
  179. for test in dir(mod):
  180. if test.startswith('test_') and hasattr(vars(mod)[test], '__call__'):
  181. # Get test case id and feature tag
  182. # NOTE: if testcase decorator or feature tag not set will throw error
  183. try:
  184. tid = vars(mod)[test].test_case
  185. except:
  186. print('DEBUG: tc id missing for ' + str(test))
  187. tid = None
  188. try:
  189. ttag = vars(mod)[test].tag__feature
  190. except:
  191. # print('DEBUG: feature tag missing for ' + str(test))
  192. ttag = None
  193. # NOTE: for some reason lstrip() doesn't work for mod.__module__
  194. tlist.append(Tc(test, mod.__name__, mod.__module__.replace(prefix, ''), tid, ttag))
  195. except:
  196. pass
  197. return tlist
  198. def get_all_tests():
  199. # Get all the test modules (except the hidden ones)
  200. testlist = []
  201. tests_modules = get_tests_modules()
  202. # Get all the tests from modules
  203. for tmod in sorted(tests_modules):
  204. testlist += get_tests_from_module(tmod)
  205. return testlist
  206. def get_testsuite_by(criteria, keyword):
  207. # Get a testsuite based on 'keyword'
  208. # criteria: name, class, module, id, tag
  209. # keyword: a list of tests, classes, modules, ids, tags
  210. ts = []
  211. all_tests = get_all_tests()
  212. def get_matches(values):
  213. # Get an item and return the ones that match with keyword(s)
  214. # values: the list of items (names, modules, classes...)
  215. result = []
  216. remaining = values[:]
  217. for key in keyword:
  218. if key in remaining:
  219. # Regular matching of exact item
  220. result.append(key)
  221. remaining.remove(key)
  222. else:
  223. # Wildcard matching
  224. pattern = re.compile(fnmatch.translate(r"%s" % key))
  225. added = [x for x in remaining if pattern.match(x)]
  226. result.extend(added)
  227. remaining = [x for x in remaining if x not in added]
  228. return result
  229. if criteria == 'name':
  230. names = get_matches([ tc.tcname for tc in all_tests ])
  231. ts = [ tc for tc in all_tests if tc.tcname in names ]
  232. elif criteria == 'class':
  233. classes = get_matches([ tc.tcclass for tc in all_tests ])
  234. ts = [ tc for tc in all_tests if tc.tcclass in classes ]
  235. elif criteria == 'module':
  236. modules = get_matches([ tc.tcmodule for tc in all_tests ])
  237. ts = [ tc for tc in all_tests if tc.tcmodule in modules ]
  238. elif criteria == 'id':
  239. ids = get_matches([ str(tc.tcid) for tc in all_tests ])
  240. ts = [ tc for tc in all_tests if str(tc.tcid) in ids ]
  241. elif criteria == 'tag':
  242. values = set()
  243. for tc in all_tests:
  244. # tc can have multiple tags (as tuple) otherwise str will suffice
  245. if isinstance(tc.tctag, tuple):
  246. values |= { str(tag) for tag in tc.tctag }
  247. else:
  248. values.add(str(tc.tctag))
  249. tags = get_matches(list(values))
  250. for tc in all_tests:
  251. for tag in tags:
  252. if isinstance(tc.tctag, tuple) and tag in tc.tctag:
  253. ts.append(tc)
  254. elif tag == tc.tctag:
  255. ts.append(tc)
  256. # Remove duplicates from the list
  257. ts = list(set(ts))
  258. return ts
  259. def list_testsuite_by(criteria, keyword):
  260. # Get a testsuite based on 'keyword'
  261. # criteria: name, class, module, id, tag
  262. # keyword: a list of tests, classes, modules, ids, tags
  263. ts = sorted([ (tc.tcid, tc.tctag, tc.tcname, tc.tcclass, tc.tcmodule) for tc in get_testsuite_by(criteria, keyword) ])
  264. print('%-4s\t%-20s\t%-60s\t%-25s\t%-20s' % ('id', 'tag', 'name', 'class', 'module'))
  265. print('_' * 150)
  266. for t in ts:
  267. if isinstance(t[1], (tuple, list)):
  268. print('%-4s\t%-20s\t%-60s\t%-25s\t%-20s' % (t[0], ', '.join(t[1]), t[2], t[3], t[4]))
  269. else:
  270. print('%-4s\t%-20s\t%-60s\t%-25s\t%-20s' % t)
  271. print('_' * 150)
  272. print('Filtering by:\t %s' % criteria)
  273. print('Looking for:\t %s' % ', '.join(str(x) for x in keyword))
  274. print('Total found:\t %s' % len(ts))
  275. def list_tests():
  276. # List all available oe-selftest tests
  277. ts = get_all_tests()
  278. print('%-4s\t%-10s\t%-50s' % ('id', 'tag', 'test'))
  279. print('_' * 80)
  280. for t in ts:
  281. if isinstance(t.tctag, (tuple, list)):
  282. print('%-4s\t%-10s\t%-50s' % (t.tcid, ', '.join(t.tctag), '.'.join([t.tcmodule, t.tcclass, t.tcname])))
  283. else:
  284. print('%-4s\t%-10s\t%-50s' % (t.tcid, t.tctag, '.'.join([t.tcmodule, t.tcclass, t.tcname])))
  285. print('_' * 80)
  286. print('Total found:\t %s' % len(ts))
  287. def list_tags():
  288. # Get all tags set to test cases
  289. # This is useful when setting tags to test cases
  290. # The list of tags should be kept as minimal as possible
  291. tags = set()
  292. all_tests = get_all_tests()
  293. for tc in all_tests:
  294. if isinstance(tc.tctag, (tuple, list)):
  295. tags.update(set(tc.tctag))
  296. else:
  297. tags.add(tc.tctag)
  298. print('Tags:\t%s' % ', '.join(str(x) for x in tags))
  299. def coverage_setup(coverage_source, coverage_include, coverage_omit):
  300. """ Set up the coverage measurement for the testcases to be run """
  301. import datetime
  302. import subprocess
  303. builddir = os.environ.get("BUILDDIR")
  304. pokydir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  305. curcommit= subprocess.check_output(["git", "--git-dir", os.path.join(pokydir, ".git"), "rev-parse", "HEAD"]).decode('utf-8')
  306. coveragerc = "%s/.coveragerc" % builddir
  307. data_file = "%s/.coverage." % builddir
  308. data_file += datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
  309. if os.path.isfile(data_file):
  310. os.remove(data_file)
  311. with open(coveragerc, 'w') as cps:
  312. cps.write("# Generated with command '%s'\n" % " ".join(sys.argv))
  313. cps.write("# HEAD commit %s\n" % curcommit.strip())
  314. cps.write("[run]\n")
  315. cps.write("data_file = %s\n" % data_file)
  316. cps.write("branch = True\n")
  317. # Measure just BBLAYERS, scripts and bitbake folders
  318. cps.write("source = \n")
  319. if coverage_source:
  320. for directory in coverage_source:
  321. if not os.path.isdir(directory):
  322. log.warn("Directory %s is not valid.", directory)
  323. cps.write(" %s\n" % directory)
  324. else:
  325. for layer in get_bb_var('BBLAYERS').split():
  326. cps.write(" %s\n" % layer)
  327. cps.write(" %s\n" % os.path.dirname(os.path.realpath(__file__)))
  328. cps.write(" %s\n" % os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),'bitbake'))
  329. if coverage_include:
  330. cps.write("include = \n")
  331. for pattern in coverage_include:
  332. cps.write(" %s\n" % pattern)
  333. if coverage_omit:
  334. cps.write("omit = \n")
  335. for pattern in coverage_omit:
  336. cps.write(" %s\n" % pattern)
  337. return coveragerc
  338. def coverage_report():
  339. """ Loads the coverage data gathered and reports it back """
  340. try:
  341. # Coverage4 uses coverage.Coverage
  342. from coverage import Coverage
  343. except:
  344. # Coverage under version 4 uses coverage.coverage
  345. from coverage import coverage as Coverage
  346. import io as StringIO
  347. from coverage.misc import CoverageException
  348. cov_output = StringIO.StringIO()
  349. # Creating the coverage data with the setting from the configuration file
  350. cov = Coverage(config_file = os.environ.get('COVERAGE_PROCESS_START'))
  351. try:
  352. # Load data from the data file specified in the configuration
  353. cov.load()
  354. # Store report data in a StringIO variable
  355. cov.report(file = cov_output, show_missing=False)
  356. log.info("\n%s" % cov_output.getvalue())
  357. except CoverageException as e:
  358. # Show problems with the reporting. Since Coverage4 not finding any data to report raises an exception
  359. log.warn("%s" % str(e))
  360. finally:
  361. cov_output.close()
  362. def main():
  363. parser = get_args_parser()
  364. args = parser.parse_args()
  365. # Add <layer>/lib to sys.path, so layers can add selftests
  366. log.info("Running bitbake -e to get BBPATH")
  367. bbpath = get_bb_var('BBPATH').split(':')
  368. layer_libdirs = [p for p in (os.path.join(l, 'lib') for l in bbpath) if os.path.exists(p)]
  369. sys.path.extend(layer_libdirs)
  370. imp.reload(oeqa.selftest)
  371. if args.run_tests_by and len(args.run_tests_by) >= 2:
  372. valid_options = ['name', 'class', 'module', 'id', 'tag']
  373. if args.run_tests_by[0] not in valid_options:
  374. print('--run-tests-by %s not a valid option. Choose one of <name|class|module|id|tag>.' % args.run_tests_by[0])
  375. return 1
  376. else:
  377. criteria = args.run_tests_by[0]
  378. keyword = args.run_tests_by[1:]
  379. ts = sorted([ tc.fullpath for tc in get_testsuite_by(criteria, keyword) ])
  380. if args.list_tests_by and len(args.list_tests_by) >= 2:
  381. valid_options = ['name', 'class', 'module', 'id', 'tag']
  382. if args.list_tests_by[0] not in valid_options:
  383. print('--list-tests-by %s not a valid option. Choose one of <name|class|module|id|tag>.' % args.list_tests_by[0])
  384. return 1
  385. else:
  386. criteria = args.list_tests_by[0]
  387. keyword = args.list_tests_by[1:]
  388. list_testsuite_by(criteria, keyword)
  389. if args.list_tests:
  390. list_tests()
  391. if args.list_tags:
  392. list_tags()
  393. if args.list_allclasses:
  394. args.list_modules = True
  395. if args.list_modules:
  396. log.info('Listing all available test modules:')
  397. testslist = get_tests(include_hidden=True)
  398. for test in testslist:
  399. module = test.split('oeqa.selftest.')[-1]
  400. info = ''
  401. if module.startswith('_'):
  402. info = ' (hidden)'
  403. print(module + info)
  404. if args.list_allclasses:
  405. try:
  406. import importlib
  407. modlib = importlib.import_module(test)
  408. for v in vars(modlib):
  409. t = vars(modlib)[v]
  410. if isinstance(t, type(oeSelfTest)) and issubclass(t, oeSelfTest) and t!=oeSelfTest:
  411. print(" --", v)
  412. for method in dir(t):
  413. if method.startswith("test_") and isinstance(vars(t)[method], collections.Callable):
  414. print(" -- --", method)
  415. except (AttributeError, ImportError) as e:
  416. print(e)
  417. pass
  418. if args.run_tests or args.run_all_tests or args.run_tests_by:
  419. if not preflight_check():
  420. return 1
  421. if args.run_tests_by:
  422. testslist = ts
  423. else:
  424. testslist = get_tests(exclusive_modules=(args.run_tests or []), include_hidden=False)
  425. suite = unittest.TestSuite()
  426. loader = unittest.TestLoader()
  427. loader.sortTestMethodsUsing = None
  428. runner = unittest.TextTestRunner(verbosity=2, resultclass=buildResultClass(args))
  429. # we need to do this here, otherwise just loading the tests
  430. # will take 2 minutes (bitbake -e calls)
  431. oeSelfTest.testlayer_path = get_test_layer()
  432. for test in testslist:
  433. log.info("Loading tests from: %s" % test)
  434. try:
  435. suite.addTests(loader.loadTestsFromName(test))
  436. except AttributeError as e:
  437. log.error("Failed to import %s" % test)
  438. log.error(e)
  439. return 1
  440. add_include()
  441. if args.machine:
  442. # Custom machine sets only weak default values (??=) for MACHINE in machine.inc
  443. # This let test cases that require a specific MACHINE to be able to override it, using (?= or =)
  444. log.info('Custom machine mode enabled. MACHINE set to %s' % args.machine)
  445. if args.machine == 'random':
  446. os.environ['CUSTOMMACHINE'] = 'random'
  447. result = runner.run(suite)
  448. else: # all
  449. machines = get_available_machines()
  450. for m in machines:
  451. log.info('Run tests with custom MACHINE set to: %s' % m)
  452. os.environ['CUSTOMMACHINE'] = m
  453. result = runner.run(suite)
  454. else:
  455. result = runner.run(suite)
  456. log.info("Finished")
  457. if result.wasSuccessful():
  458. return 0
  459. else:
  460. return 1
  461. def buildResultClass(args):
  462. """Build a Result Class to use in the testcase execution"""
  463. import site
  464. class StampedResult(unittest.TextTestResult):
  465. """
  466. Custom TestResult that prints the time when a test starts. As oe-selftest
  467. can take a long time (ie a few hours) to run, timestamps help us understand
  468. what tests are taking a long time to execute.
  469. If coverage is required, this class executes the coverage setup and reporting.
  470. """
  471. def startTest(self, test):
  472. import time
  473. self.stream.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + " - ")
  474. super(StampedResult, self).startTest(test)
  475. def startTestRun(self):
  476. """ Setup coverage before running any testcase """
  477. # variable holding the coverage configuration file allowing subprocess to be measured
  478. self.coveragepth = None
  479. # indicates the system if coverage is currently installed
  480. self.coverage_installed = True
  481. if args.coverage or args.coverage_source or args.coverage_include or args.coverage_omit:
  482. try:
  483. # check if user can do coverage
  484. import coverage
  485. except:
  486. log.warn("python coverage is not installed. More info on https://pypi.python.org/pypi/coverage")
  487. self.coverage_installed = False
  488. if self.coverage_installed:
  489. log.info("Coverage is enabled")
  490. # In case the user has not set the variable COVERAGE_PROCESS_START,
  491. # create a default one and export it. The COVERAGE_PROCESS_START
  492. # value indicates where the coverage configuration file resides
  493. # More info on https://pypi.python.org/pypi/coverage
  494. if not os.environ.get('COVERAGE_PROCESS_START'):
  495. os.environ['COVERAGE_PROCESS_START'] = coverage_setup(args.coverage_source, args.coverage_include, args.coverage_omit)
  496. # Use default site.USER_SITE and write corresponding config file
  497. site.ENABLE_USER_SITE = True
  498. if not os.path.exists(site.USER_SITE):
  499. os.makedirs(site.USER_SITE)
  500. self.coveragepth = os.path.join(site.USER_SITE, "coverage.pth")
  501. with open(self.coveragepth, 'w') as cps:
  502. cps.write('import sys,site; sys.path.extend(site.getsitepackages()); import coverage; coverage.process_startup();')
  503. def stopTestRun(self):
  504. """ Report coverage data after the testcases are run """
  505. if args.coverage or args.coverage_source or args.coverage_include or args.coverage_omit:
  506. if self.coverage_installed:
  507. with open(os.environ['COVERAGE_PROCESS_START']) as ccf:
  508. log.info("Coverage configuration file (%s)" % os.environ.get('COVERAGE_PROCESS_START'))
  509. log.info("===========================")
  510. log.info("\n%s" % "".join(ccf.readlines()))
  511. log.info("Coverage Report")
  512. log.info("===============")
  513. try:
  514. coverage_report()
  515. finally:
  516. # remove the pth file
  517. try:
  518. os.remove(self.coveragepth)
  519. except OSError:
  520. log.warn("Expected temporal file from coverage is missing, ignoring removal.")
  521. return StampedResult
  522. if __name__ == "__main__":
  523. try:
  524. ret = main()
  525. except Exception:
  526. ret = 1
  527. import traceback
  528. traceback.print_exc()
  529. finally:
  530. remove_include()
  531. remove_inc_files()
  532. sys.exit(ret)