Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 2 | |
| 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 19 | # This script runs tests defined in meta/lib/oeqa/selftest/ |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 20 | # 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 23 | # 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 26 | |
| 27 | |
| 28 | import os |
| 29 | import sys |
| 30 | import unittest |
| 31 | import logging |
| 32 | import argparse |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 33 | import subprocess |
| 34 | import time as t |
| 35 | import re |
| 36 | import fnmatch |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 37 | import collections |
| 38 | import imp |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 39 | |
| 40 | sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + '/lib') |
| 41 | import scriptpath |
| 42 | scriptpath.add_bitbake_lib_path() |
| 43 | scriptpath.add_oe_lib_path() |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 44 | import argparse_oe |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 45 | |
| 46 | import oeqa.selftest |
| 47 | import oeqa.utils.ftools as ftools |
| 48 | from oeqa.utils.commands import runCmd, get_bb_var, get_test_layer |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 49 | from oeqa.utils.metadata import metadata_from_bb, write_metadata_file |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 50 | from oeqa.selftest.base import oeSelfTest, get_available_machines |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 51 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 52 | try: |
| 53 | import xmlrunner |
| 54 | from xmlrunner.result import _XMLTestResult as TestResult |
| 55 | from xmlrunner import XMLTestRunner as _TestRunner |
| 56 | except ImportError: |
| 57 | # use the base runner instead |
| 58 | from unittest import TextTestResult as TestResult |
| 59 | from unittest import TextTestRunner as _TestRunner |
| 60 | |
| 61 | log_prefix = "oe-selftest-" + t.strftime("%Y%m%d-%H%M%S") |
| 62 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 63 | def logger_create(): |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 64 | log_file = log_prefix + ".log" |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 65 | if os.path.lexists("oe-selftest.log"): |
| 66 | os.remove("oe-selftest.log") |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 67 | os.symlink(log_file, "oe-selftest.log") |
| 68 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 69 | log = logging.getLogger("selftest") |
| 70 | log.setLevel(logging.DEBUG) |
| 71 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 72 | fh = logging.FileHandler(filename=log_file, mode='w') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 73 | 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 | |
| 87 | log = logger_create() |
| 88 | |
| 89 | def get_args_parser(): |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 90 | 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 91 | parser = argparse_oe.ArgumentParser(description=description) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 92 | group = parser.add_mutually_exclusive_group(required=True) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 93 | 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 96 | group.add_argument('--list-classes', required=False, action="store_true", dest="list_allclasses", default=False, help='List all available test classes.') |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 97 | 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 Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 111 | parser.add_argument('--repository', required=False, dest='repository', default='', action='store', |
| 112 | help='Submit test results to a repository') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 113 | return parser |
| 114 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 115 | builddir = None |
| 116 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 117 | |
| 118 | def preflight_check(): |
| 119 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 120 | global builddir |
| 121 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 122 | 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 Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 134 | 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 155 | return False |
| 156 | |
| 157 | log.info("Running bitbake -p") |
| 158 | runCmd("bitbake -p") |
| 159 | |
| 160 | return True |
| 161 | |
| 162 | def add_include(): |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 163 | global builddir |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 164 | 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 168 | "\n#include added by oe-selftest.py\ninclude machine.inc\ninclude selftest.inc") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 169 | |
| 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 | |
| 176 | def remove_include(): |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 177 | global builddir |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 178 | 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 184 | "\n#include added by oe-selftest.py\ninclude machine.inc\ninclude selftest.inc") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 185 | |
| 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 190 | "\n#include added by oe-selftest.py\ninclude bblayers.inc") |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 191 | |
| 192 | def remove_inc_files(): |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 193 | global builddir |
| 194 | if builddir is None: |
| 195 | return |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 196 | try: |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 197 | os.remove(os.path.join(builddir, "conf/selftest.inc")) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 198 | 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 Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 202 | except OSError as e: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 203 | pass |
| 204 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 205 | for incl_file in ['conf/bblayers.inc', 'conf/machine.inc']: |
| 206 | try: |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 207 | os.remove(os.path.join(builddir, incl_file)) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 208 | except: |
| 209 | pass |
| 210 | |
| 211 | |
| 212 | def 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 | |
| 229 | def 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 | |
| 240 | class 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 | |
| 251 | def get_tests_from_module(tmod): |
| 252 | tlist = [] |
| 253 | prefix = 'oeqa.selftest.' |
| 254 | |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 255 | try: |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 256 | import importlib |
| 257 | modlib = importlib.import_module(tmod) |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 258 | for mod in list(vars(modlib).values()): |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 259 | 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 267 | print('DEBUG: tc id missing for ' + str(test)) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 268 | tid = None |
| 269 | try: |
| 270 | ttag = vars(mod)[test].tag__feature |
| 271 | except: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 272 | # print('DEBUG: feature tag missing for ' + str(test)) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 273 | 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 277 | except: |
| 278 | pass |
| 279 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 280 | return tlist |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 281 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 282 | |
| 283 | def 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 | |
| 293 | def 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 307 | found = False |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 308 | if key in remaining: |
| 309 | # Regular matching of exact item |
| 310 | result.append(key) |
| 311 | remaining.remove(key) |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 312 | found = True |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 313 | 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 317 | 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 323 | |
| 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 | |
| 366 | def 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 Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 370 | 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 379 | print('_' * 150) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 380 | for t in ts: |
| 381 | if isinstance(t[1], (tuple, list)): |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 382 | print('%-4s\t%-20s\t%-60s\t%-25s\t%-20s' % (t[0], ', '.join(t[1]), t[2], t[3], t[4])) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 383 | else: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 384 | 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 389 | |
| 390 | |
| 391 | def list_tests(): |
| 392 | # List all available oe-selftest tests |
| 393 | |
| 394 | ts = get_all_tests() |
| 395 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 396 | print('%-4s\t%-10s\t%-50s' % ('id', 'tag', 'test')) |
| 397 | print('_' * 80) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 398 | for t in ts: |
| 399 | if isinstance(t.tctag, (tuple, list)): |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 400 | print('%-4s\t%-10s\t%-50s' % (t.tcid, ', '.join(t.tctag), '.'.join([t.tcmodule, t.tcclass, t.tcname]))) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 401 | else: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 402 | 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 405 | |
| 406 | def 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 419 | print('Tags:\t%s' % ', '.join(str(x) for x in tags)) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 420 | |
| 421 | def 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 Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 425 | global builddir |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 426 | pokydir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 427 | curcommit= subprocess.check_output(["git", "--git-dir", os.path.join(pokydir, ".git"), "rev-parse", "HEAD"]).decode('utf-8') |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 428 | 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 | |
| 463 | def 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 472 | import io as StringIO |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 473 | 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 490 | |
| 491 | def 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 500 | imp.reload(oeqa.selftest) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 501 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 502 | # act like bitbake and enforce en_US.UTF-8 locale |
| 503 | os.environ["LC_ALL"] = "en_US.UTF-8" |
| 504 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 505 | 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 508 | print('--run-tests-by %s not a valid option. Choose one of <name|class|module|id|tag>.' % args.run_tests_by[0]) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 509 | 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 514 | if not ts: |
| 515 | return 1 |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 516 | |
| 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 520 | print('--list-tests-by %s not a valid option. Choose one of <name|class|module|id|tag>.' % args.list_tests_by[0]) |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 521 | 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 533 | 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 540 | module = test.split('oeqa.selftest.')[-1] |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 541 | info = '' |
| 542 | if module.startswith('_'): |
| 543 | info = ' (hidden)' |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 544 | print(module + info) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 545 | 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 552 | print(" --", v) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 553 | for method in dir(t): |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 554 | if method.startswith("test_") and isinstance(vars(t)[method], collections.Callable): |
| 555 | print(" -- --", method) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 556 | |
| 557 | except (AttributeError, ImportError) as e: |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 558 | print(e) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 559 | pass |
| 560 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 561 | if args.run_tests or args.run_all_tests or args.run_tests_by: |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 562 | if not preflight_check(): |
| 563 | return 1 |
| 564 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 565 | 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 570 | suite = unittest.TestSuite() |
| 571 | loader = unittest.TestLoader() |
| 572 | loader.sortTestMethodsUsing = None |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 573 | runner = TestRunner(verbosity=2, |
| 574 | resultclass=buildResultClass(args)) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 575 | # 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 587 | |
| 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 604 | log.info("Finished") |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 605 | |
Brad Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 606 | 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 676 | if result.wasSuccessful(): |
| 677 | return 0 |
| 678 | else: |
| 679 | return 1 |
| 680 | |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 681 | def buildResultClass(args): |
| 682 | """Build a Result Class to use in the testcase execution""" |
| 683 | import site |
| 684 | |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 685 | class StampedResult(TestResult): |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 686 | """ |
| 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 717 | 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 721 | # 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 Bishop | 6e60e8b | 2018-02-01 10:27:11 -0500 | [diff] [blame^] | 759 | def 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 | |
| 770 | def 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 788 | class 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 803 | |
| 804 | if __name__ == "__main__": |
| 805 | try: |
| 806 | ret = main() |
| 807 | except Exception: |
| 808 | ret = 1 |
| 809 | import traceback |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 810 | traceback.print_exc() |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 811 | finally: |
| 812 | remove_include() |
| 813 | remove_inc_files() |
| 814 | sys.exit(ret) |