Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 1 | # SPDX-License-Identifier: GPL-2.0+ |
| 2 | # |
| 3 | # Copyright (c) 2016 Google, Inc |
| 4 | # |
| 5 | |
Simon Glass | c27d22d | 2022-01-22 05:07:28 -0700 | [diff] [blame] | 6 | import doctest |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 7 | import glob |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 8 | import multiprocessing |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 9 | import os |
Simon Glass | 66827cc | 2025-04-10 06:43:04 -0600 | [diff] [blame] | 10 | import re |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 11 | import sys |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 12 | import unittest |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 13 | |
Simon Glass | 131444f | 2023-02-23 18:18:04 -0700 | [diff] [blame] | 14 | from u_boot_pylib import command |
Simon Glass | 17899e4 | 2025-04-29 07:22:06 -0600 | [diff] [blame^] | 15 | from u_boot_pylib import terminal |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 16 | |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 17 | use_concurrent = True |
| 18 | try: |
Simon Glass | f715ab9 | 2023-02-23 18:18:03 -0700 | [diff] [blame] | 19 | from concurrencytest import ConcurrentTestSuite |
| 20 | from concurrencytest import fork_for_tests |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 21 | except: |
| 22 | use_concurrent = False |
| 23 | |
Simon Glass | 3609d5e | 2018-07-06 10:27:34 -0600 | [diff] [blame] | 24 | |
Simon Glass | 0ce8fed | 2024-09-30 12:51:36 -0600 | [diff] [blame] | 25 | def run_test_coverage(prog, filter_fname, exclude_list, build_dir, |
| 26 | required=None, extra_args=None, single_thread='-P1', |
Simon Glass | 66827cc | 2025-04-10 06:43:04 -0600 | [diff] [blame] | 27 | args=None, allow_failures=None): |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 28 | """Run tests and check that we get 100% coverage |
| 29 | |
| 30 | Args: |
| 31 | prog: Program to run (with be passed a '-t' argument to run tests |
| 32 | filter_fname: Normally all *.py files in the program's directory will |
| 33 | be included. If this is not None, then it is used to filter the |
| 34 | list so that only filenames that don't contain filter_fname are |
| 35 | included. |
| 36 | exclude_list: List of file patterns to exclude from the coverage |
| 37 | calculation |
| 38 | build_dir: Build directory, used to locate libfdt.py |
| 39 | required: List of modules which must be in the coverage report |
Simon Glass | 5d5930d | 2020-07-09 18:39:29 -0600 | [diff] [blame] | 40 | extra_args (str): Extra arguments to pass to the tool before the -t/test |
| 41 | arg |
Simon Glass | c8b99b1 | 2023-07-19 17:49:31 -0600 | [diff] [blame] | 42 | single_thread (str): Argument string to make the tests run |
| 43 | single-threaded. This is necessary to get proper coverage results. |
| 44 | The default is '-P0' |
Simon Glass | 0ce8fed | 2024-09-30 12:51:36 -0600 | [diff] [blame] | 45 | args (list of str): List of tests to run, or None to run all |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 46 | |
| 47 | Raises: |
| 48 | ValueError if the code coverage is not 100% |
| 49 | """ |
| 50 | # This uses the build output from sandbox_spl to get _libfdt.so |
| 51 | path = os.path.dirname(prog) |
| 52 | if filter_fname: |
| 53 | glob_list = glob.glob(os.path.join(path, '*.py')) |
| 54 | glob_list = [fname for fname in glob_list if filter_fname in fname] |
| 55 | else: |
| 56 | glob_list = [] |
| 57 | glob_list += exclude_list |
Simon Glass | 0eca03c | 2025-04-10 06:42:59 -0600 | [diff] [blame] | 58 | glob_list += ['*libfdt.py', '*/site-packages/*', '*/dist-packages/*'] |
Simon Glass | 6eb63c7 | 2020-07-09 18:39:34 -0600 | [diff] [blame] | 59 | glob_list += ['*concurrencytest*'] |
Simon Glass | 109e84e | 2020-07-05 21:41:55 -0600 | [diff] [blame] | 60 | test_cmd = 'test' if 'binman' in prog or 'patman' in prog else '-t' |
Simon Glass | f156e3b | 2020-04-17 18:09:00 -0600 | [diff] [blame] | 61 | prefix = '' |
| 62 | if build_dir: |
| 63 | prefix = 'PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools ' % build_dir |
Simon Glass | bd75bea | 2024-06-23 11:56:21 -0600 | [diff] [blame] | 64 | |
Tom Rini | c02ec5a | 2025-04-15 12:10:26 -0600 | [diff] [blame] | 65 | # Detect a Python sandbox and use 'coverage' instead |
Simon Glass | bd75bea | 2024-06-23 11:56:21 -0600 | [diff] [blame] | 66 | covtool = ('python3-coverage' if sys.prefix == sys.base_prefix else |
| 67 | 'coverage') |
| 68 | |
| 69 | cmd = ('%s%s run ' |
Simon Glass | 0ce8fed | 2024-09-30 12:51:36 -0600 | [diff] [blame] | 70 | '--omit "%s" %s %s %s %s %s' % (prefix, covtool, ','.join(glob_list), |
| 71 | prog, extra_args or '', test_cmd, |
| 72 | single_thread or '-P1', |
| 73 | ' '.join(args) if args else '')) |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 74 | os.system(cmd) |
Simon Glass | bd75bea | 2024-06-23 11:56:21 -0600 | [diff] [blame] | 75 | stdout = command.output(covtool, 'report') |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 76 | lines = stdout.splitlines() |
| 77 | if required: |
| 78 | # Convert '/path/to/name.py' just the module name 'name' |
| 79 | test_set = set([os.path.splitext(os.path.basename(line.split()[0]))[0] |
| 80 | for line in lines if '/etype/' in line]) |
| 81 | missing_list = required |
Simon Glass | 0baeab7 | 2019-07-08 14:25:32 -0600 | [diff] [blame] | 82 | missing_list.discard('__init__') |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 83 | missing_list.difference_update(test_set) |
| 84 | if missing_list: |
Simon Glass | 23b8a19 | 2019-05-14 15:53:36 -0600 | [diff] [blame] | 85 | print('Missing tests for %s' % (', '.join(missing_list))) |
| 86 | print(stdout) |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 87 | ok = False |
| 88 | |
| 89 | coverage = lines[-1].split(' ')[-1] |
| 90 | ok = True |
Simon Glass | 23b8a19 | 2019-05-14 15:53:36 -0600 | [diff] [blame] | 91 | print(coverage) |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 92 | if coverage != '100%': |
Simon Glass | 23b8a19 | 2019-05-14 15:53:36 -0600 | [diff] [blame] | 93 | print(stdout) |
Simon Glass | 5881641 | 2022-08-13 11:40:41 -0600 | [diff] [blame] | 94 | print("To get a report in 'htmlcov/index.html', type: python3-coverage html") |
Simon Glass | 23b8a19 | 2019-05-14 15:53:36 -0600 | [diff] [blame] | 95 | print('Coverage error: %s, but should be 100%%' % coverage) |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 96 | ok = False |
| 97 | if not ok: |
Simon Glass | 66827cc | 2025-04-10 06:43:04 -0600 | [diff] [blame] | 98 | if allow_failures: |
| 99 | # for line in lines: |
| 100 | # print('.', line, re.match(r'^(tools/.*py) *\d+ *(\d+) *(\d+)%$', line)) |
| 101 | lines = [re.match(r'^(tools/.*py) *\d+ *(\d+) *\d+%$', line) |
| 102 | for line in stdout.splitlines()] |
| 103 | bad = [] |
| 104 | for mat in lines: |
| 105 | if mat and mat.group(2) != '0': |
| 106 | fname = mat.group(1) |
| 107 | if fname not in allow_failures: |
| 108 | bad.append(fname) |
| 109 | if not bad: |
| 110 | return |
Simon Glass | 132be85 | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 111 | raise ValueError('Test coverage failure') |
Simon Glass | 3609d5e | 2018-07-06 10:27:34 -0600 | [diff] [blame] | 112 | |
| 113 | |
Alper Nebi Yasak | fedac7b | 2022-04-02 20:06:07 +0300 | [diff] [blame] | 114 | class FullTextTestResult(unittest.TextTestResult): |
| 115 | """A test result class that can print extended text results to a stream |
| 116 | |
| 117 | This is meant to be used by a TestRunner as a result class. Like |
| 118 | TextTestResult, this prints out the names of tests as they are run, |
| 119 | errors as they occur, and a summary of the results at the end of the |
| 120 | test run. Beyond those, this prints information about skipped tests, |
| 121 | expected failures and unexpected successes. |
| 122 | |
| 123 | Args: |
| 124 | stream: A file-like object to write results to |
| 125 | descriptions (bool): True to print descriptions with test names |
| 126 | verbosity (int): Detail of printed output per test as they run |
| 127 | Test stdout and stderr always get printed when buffering |
| 128 | them is disabled by the test runner. In addition to that, |
| 129 | 0: Print nothing |
| 130 | 1: Print a dot per test |
| 131 | 2: Print test names |
| 132 | """ |
| 133 | def __init__(self, stream, descriptions, verbosity): |
| 134 | self.verbosity = verbosity |
| 135 | super().__init__(stream, descriptions, verbosity) |
| 136 | |
| 137 | def printErrors(self): |
| 138 | "Called by TestRunner after test run to summarize the tests" |
| 139 | # The parent class doesn't keep unexpected successes in the same |
| 140 | # format as the rest. Adapt it to what printErrorList expects. |
| 141 | unexpected_successes = [ |
| 142 | (test, 'Test was expected to fail, but succeeded.\n') |
| 143 | for test in self.unexpectedSuccesses |
| 144 | ] |
| 145 | |
| 146 | super().printErrors() # FAIL and ERROR |
| 147 | self.printErrorList('SKIP', self.skipped) |
| 148 | self.printErrorList('XFAIL', self.expectedFailures) |
| 149 | self.printErrorList('XPASS', unexpected_successes) |
| 150 | |
| 151 | def addSkip(self, test, reason): |
| 152 | """Called when a test is skipped.""" |
| 153 | # Add empty line to keep spacing consistent with other results |
| 154 | if not reason.endswith('\n'): |
| 155 | reason += '\n' |
| 156 | super().addSkip(test, reason) |
| 157 | |
| 158 | |
Simon Glass | 17899e4 | 2025-04-29 07:22:06 -0600 | [diff] [blame^] | 159 | def run_test_suites(toolname, debug, verbosity, no_capture, test_preserve_dirs, |
| 160 | processes, test_name, toolpath, class_and_module_list): |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 161 | """Run a series of test suites and collect the results |
| 162 | |
| 163 | Args: |
Alper Nebi Yasak | ca1c588 | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 164 | toolname: Name of the tool that ran the tests |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 165 | debug: True to enable debugging, which shows a full stack trace on error |
| 166 | verbosity: Verbosity level to use (0-4) |
| 167 | test_preserve_dirs: True to preserve the input directory used by tests |
| 168 | so that it can be examined afterwards (only useful for debugging |
| 169 | tests). If a single test is selected (in args[0]) it also preserves |
| 170 | the output directory for this test. Both directories are displayed |
| 171 | on the command line. |
| 172 | processes: Number of processes to use to run tests (None=same as #CPUs) |
| 173 | test_name: Name of test to run, or None for all |
| 174 | toolpath: List of paths to use for tools |
Simon Glass | c27d22d | 2022-01-22 05:07:28 -0700 | [diff] [blame] | 175 | class_and_module_list: List of test classes (type class) and module |
| 176 | names (type str) to run |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 177 | """ |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 178 | sys.argv = [sys.argv[0]] |
| 179 | if debug: |
| 180 | sys.argv.append('-D') |
| 181 | if verbosity: |
| 182 | sys.argv.append('-v%d' % verbosity) |
Simon Glass | 17899e4 | 2025-04-29 07:22:06 -0600 | [diff] [blame^] | 183 | if no_capture: |
| 184 | sys.argv.append('-N') |
| 185 | terminal.USE_CAPTURE = False |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 186 | if toolpath: |
| 187 | for path in toolpath: |
| 188 | sys.argv += ['--toolpath', path] |
| 189 | |
| 190 | suite = unittest.TestSuite() |
| 191 | loader = unittest.TestLoader() |
Alper Nebi Yasak | ca1c588 | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 192 | runner = unittest.TextTestRunner( |
| 193 | stream=sys.stdout, |
| 194 | verbosity=(1 if verbosity is None else verbosity), |
Alper Nebi Yasak | fedac7b | 2022-04-02 20:06:07 +0300 | [diff] [blame] | 195 | resultclass=FullTextTestResult, |
Alper Nebi Yasak | ca1c588 | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 196 | ) |
| 197 | |
Simon Glass | 4d185c0 | 2025-04-29 07:22:04 -0600 | [diff] [blame] | 198 | if use_concurrent and processes != 1 and not test_name: |
Alper Nebi Yasak | ca1c588 | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 199 | suite = ConcurrentTestSuite(suite, |
Simon Glass | 1ca554e | 2023-02-23 18:18:02 -0700 | [diff] [blame] | 200 | fork_for_tests(processes or multiprocessing.cpu_count())) |
Alper Nebi Yasak | ca1c588 | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 201 | |
| 202 | for module in class_and_module_list: |
| 203 | if isinstance(module, str) and (not test_name or test_name == module): |
| 204 | suite.addTests(doctest.DocTestSuite(module)) |
| 205 | |
Simon Glass | c27d22d | 2022-01-22 05:07:28 -0700 | [diff] [blame] | 206 | for module in class_and_module_list: |
| 207 | if isinstance(module, str): |
| 208 | continue |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 209 | # Test the test module about our arguments, if it is interested |
| 210 | if hasattr(module, 'setup_test_args'): |
| 211 | setup_test_args = getattr(module, 'setup_test_args') |
| 212 | setup_test_args(preserve_indir=test_preserve_dirs, |
| 213 | preserve_outdirs=test_preserve_dirs and test_name is not None, |
Simon Glass | 17899e4 | 2025-04-29 07:22:06 -0600 | [diff] [blame^] | 214 | toolpath=toolpath, verbosity=verbosity, no_capture=no_capture) |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 215 | if test_name: |
Alper Nebi Yasak | 71e9a4c | 2022-04-02 20:06:05 +0300 | [diff] [blame] | 216 | # Since Python v3.5 If an ImportError or AttributeError occurs |
| 217 | # while traversing a name then a synthetic test that raises that |
| 218 | # error when run will be returned. Check that the requested test |
| 219 | # exists, otherwise these errors are included in the results. |
| 220 | if test_name in loader.getTestCaseNames(module): |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 221 | suite.addTests(loader.loadTestsFromName(test_name, module)) |
Simon Glass | 7330692 | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 222 | else: |
| 223 | suite.addTests(loader.loadTestsFromTestCase(module)) |
Alper Nebi Yasak | ca1c588 | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 224 | |
| 225 | print(f" Running {toolname} tests ".center(70, "=")) |
| 226 | result = runner.run(suite) |
| 227 | print() |
| 228 | |
| 229 | return result |