Simon Glass | ff1fd6c | 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 | c3f9454 | 2018-07-06 10:27:34 -0600 | [diff] [blame] | 6 | from contextlib import contextmanager |
Simon Glass | 1d0f30e | 2022-01-22 05:07:28 -0700 | [diff] [blame] | 7 | import doctest |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 8 | import glob |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 9 | import multiprocessing |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 10 | import os |
| 11 | import sys |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 12 | import unittest |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 13 | |
Simon Glass | bf77667 | 2020-04-17 18:09:04 -0600 | [diff] [blame] | 14 | from patman import command |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 15 | |
Simon Glass | c3a13cc | 2020-04-17 18:08:55 -0600 | [diff] [blame] | 16 | from io import StringIO |
Simon Glass | c3f9454 | 2018-07-06 10:27:34 -0600 | [diff] [blame] | 17 | |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 18 | use_concurrent = True |
| 19 | try: |
Simon Glass | 347e0f0 | 2020-07-09 18:39:34 -0600 | [diff] [blame] | 20 | from concurrencytest.concurrencytest import ConcurrentTestSuite |
| 21 | from concurrencytest.concurrencytest import fork_for_tests |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 22 | except: |
| 23 | use_concurrent = False |
| 24 | |
Simon Glass | c3f9454 | 2018-07-06 10:27:34 -0600 | [diff] [blame] | 25 | |
Simon Glass | 5e2ab40 | 2022-01-29 14:14:14 -0700 | [diff] [blame] | 26 | def run_test_coverage(prog, filter_fname, exclude_list, build_dir, required=None, |
Simon Glass | 32eb66d | 2020-07-09 18:39:29 -0600 | [diff] [blame] | 27 | extra_args=None): |
Simon Glass | ff1fd6c | 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 | 32eb66d | 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 | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 42 | |
| 43 | Raises: |
| 44 | ValueError if the code coverage is not 100% |
| 45 | """ |
| 46 | # This uses the build output from sandbox_spl to get _libfdt.so |
| 47 | path = os.path.dirname(prog) |
| 48 | if filter_fname: |
| 49 | glob_list = glob.glob(os.path.join(path, '*.py')) |
| 50 | glob_list = [fname for fname in glob_list if filter_fname in fname] |
| 51 | else: |
| 52 | glob_list = [] |
| 53 | glob_list += exclude_list |
Simon Glass | 9550f9a | 2019-05-17 22:00:54 -0600 | [diff] [blame] | 54 | glob_list += ['*libfdt.py', '*site-packages*', '*dist-packages*'] |
Simon Glass | 347e0f0 | 2020-07-09 18:39:34 -0600 | [diff] [blame] | 55 | glob_list += ['*concurrencytest*'] |
Simon Glass | 6bb74de | 2020-07-05 21:41:55 -0600 | [diff] [blame] | 56 | test_cmd = 'test' if 'binman' in prog or 'patman' in prog else '-t' |
Simon Glass | 428e773 | 2020-04-17 18:09:00 -0600 | [diff] [blame] | 57 | prefix = '' |
| 58 | if build_dir: |
| 59 | prefix = 'PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools ' % build_dir |
| 60 | cmd = ('%spython3-coverage run ' |
Simon Glass | 32eb66d | 2020-07-09 18:39:29 -0600 | [diff] [blame] | 61 | '--omit "%s" %s %s %s -P1' % (prefix, ','.join(glob_list), |
| 62 | prog, extra_args or '', test_cmd)) |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 63 | os.system(cmd) |
Simon Glass | d980069 | 2022-01-29 14:14:05 -0700 | [diff] [blame] | 64 | stdout = command.output('python3-coverage', 'report') |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 65 | lines = stdout.splitlines() |
| 66 | if required: |
| 67 | # Convert '/path/to/name.py' just the module name 'name' |
| 68 | test_set = set([os.path.splitext(os.path.basename(line.split()[0]))[0] |
| 69 | for line in lines if '/etype/' in line]) |
| 70 | missing_list = required |
Simon Glass | e430440 | 2019-07-08 14:25:32 -0600 | [diff] [blame] | 71 | missing_list.discard('__init__') |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 72 | missing_list.difference_update(test_set) |
| 73 | if missing_list: |
Simon Glass | 5a1af1d | 2019-05-14 15:53:36 -0600 | [diff] [blame] | 74 | print('Missing tests for %s' % (', '.join(missing_list))) |
| 75 | print(stdout) |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 76 | ok = False |
| 77 | |
| 78 | coverage = lines[-1].split(' ')[-1] |
| 79 | ok = True |
Simon Glass | 5a1af1d | 2019-05-14 15:53:36 -0600 | [diff] [blame] | 80 | print(coverage) |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 81 | if coverage != '100%': |
Simon Glass | 5a1af1d | 2019-05-14 15:53:36 -0600 | [diff] [blame] | 82 | print(stdout) |
Simon Glass | 428e773 | 2020-04-17 18:09:00 -0600 | [diff] [blame] | 83 | print("Type 'python3-coverage html' to get a report in " |
| 84 | 'htmlcov/index.html') |
Simon Glass | 5a1af1d | 2019-05-14 15:53:36 -0600 | [diff] [blame] | 85 | print('Coverage error: %s, but should be 100%%' % coverage) |
Simon Glass | ff1fd6c | 2018-07-06 10:27:23 -0600 | [diff] [blame] | 86 | ok = False |
| 87 | if not ok: |
| 88 | raise ValueError('Test coverage failure') |
Simon Glass | c3f9454 | 2018-07-06 10:27:34 -0600 | [diff] [blame] | 89 | |
| 90 | |
| 91 | # Use this to suppress stdout/stderr output: |
| 92 | # with capture_sys_output() as (stdout, stderr) |
| 93 | # ...do something... |
| 94 | @contextmanager |
| 95 | def capture_sys_output(): |
| 96 | capture_out, capture_err = StringIO(), StringIO() |
| 97 | old_out, old_err = sys.stdout, sys.stderr |
| 98 | try: |
| 99 | sys.stdout, sys.stderr = capture_out, capture_err |
| 100 | yield capture_out, capture_err |
| 101 | finally: |
| 102 | sys.stdout, sys.stderr = old_out, old_err |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 103 | |
| 104 | |
Alper Nebi Yasak | dd6b92b | 2022-04-02 20:06:07 +0300 | [diff] [blame^] | 105 | class FullTextTestResult(unittest.TextTestResult): |
| 106 | """A test result class that can print extended text results to a stream |
| 107 | |
| 108 | This is meant to be used by a TestRunner as a result class. Like |
| 109 | TextTestResult, this prints out the names of tests as they are run, |
| 110 | errors as they occur, and a summary of the results at the end of the |
| 111 | test run. Beyond those, this prints information about skipped tests, |
| 112 | expected failures and unexpected successes. |
| 113 | |
| 114 | Args: |
| 115 | stream: A file-like object to write results to |
| 116 | descriptions (bool): True to print descriptions with test names |
| 117 | verbosity (int): Detail of printed output per test as they run |
| 118 | Test stdout and stderr always get printed when buffering |
| 119 | them is disabled by the test runner. In addition to that, |
| 120 | 0: Print nothing |
| 121 | 1: Print a dot per test |
| 122 | 2: Print test names |
| 123 | """ |
| 124 | def __init__(self, stream, descriptions, verbosity): |
| 125 | self.verbosity = verbosity |
| 126 | super().__init__(stream, descriptions, verbosity) |
| 127 | |
| 128 | def printErrors(self): |
| 129 | "Called by TestRunner after test run to summarize the tests" |
| 130 | # The parent class doesn't keep unexpected successes in the same |
| 131 | # format as the rest. Adapt it to what printErrorList expects. |
| 132 | unexpected_successes = [ |
| 133 | (test, 'Test was expected to fail, but succeeded.\n') |
| 134 | for test in self.unexpectedSuccesses |
| 135 | ] |
| 136 | |
| 137 | super().printErrors() # FAIL and ERROR |
| 138 | self.printErrorList('SKIP', self.skipped) |
| 139 | self.printErrorList('XFAIL', self.expectedFailures) |
| 140 | self.printErrorList('XPASS', unexpected_successes) |
| 141 | |
| 142 | def addSkip(self, test, reason): |
| 143 | """Called when a test is skipped.""" |
| 144 | # Add empty line to keep spacing consistent with other results |
| 145 | if not reason.endswith('\n'): |
| 146 | reason += '\n' |
| 147 | super().addSkip(test, reason) |
| 148 | |
| 149 | |
Alper Nebi Yasak | d8318fe | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 150 | def run_test_suites(toolname, debug, verbosity, test_preserve_dirs, processes, |
Simon Glass | 5e2ab40 | 2022-01-29 14:14:14 -0700 | [diff] [blame] | 151 | test_name, toolpath, class_and_module_list): |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 152 | """Run a series of test suites and collect the results |
| 153 | |
| 154 | Args: |
Alper Nebi Yasak | d8318fe | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 155 | toolname: Name of the tool that ran the tests |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 156 | debug: True to enable debugging, which shows a full stack trace on error |
| 157 | verbosity: Verbosity level to use (0-4) |
| 158 | test_preserve_dirs: True to preserve the input directory used by tests |
| 159 | so that it can be examined afterwards (only useful for debugging |
| 160 | tests). If a single test is selected (in args[0]) it also preserves |
| 161 | the output directory for this test. Both directories are displayed |
| 162 | on the command line. |
| 163 | processes: Number of processes to use to run tests (None=same as #CPUs) |
| 164 | test_name: Name of test to run, or None for all |
| 165 | toolpath: List of paths to use for tools |
Simon Glass | 1d0f30e | 2022-01-22 05:07:28 -0700 | [diff] [blame] | 166 | class_and_module_list: List of test classes (type class) and module |
| 167 | names (type str) to run |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 168 | """ |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 169 | sys.argv = [sys.argv[0]] |
| 170 | if debug: |
| 171 | sys.argv.append('-D') |
| 172 | if verbosity: |
| 173 | sys.argv.append('-v%d' % verbosity) |
| 174 | if toolpath: |
| 175 | for path in toolpath: |
| 176 | sys.argv += ['--toolpath', path] |
| 177 | |
| 178 | suite = unittest.TestSuite() |
| 179 | loader = unittest.TestLoader() |
Alper Nebi Yasak | d8318fe | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 180 | runner = unittest.TextTestRunner( |
| 181 | stream=sys.stdout, |
| 182 | verbosity=(1 if verbosity is None else verbosity), |
Alper Nebi Yasak | dd6b92b | 2022-04-02 20:06:07 +0300 | [diff] [blame^] | 183 | resultclass=FullTextTestResult, |
Alper Nebi Yasak | d8318fe | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 184 | ) |
| 185 | |
| 186 | if use_concurrent and processes != 1: |
| 187 | suite = ConcurrentTestSuite(suite, |
| 188 | fork_for_tests(processes or multiprocessing.cpu_count())) |
| 189 | |
| 190 | for module in class_and_module_list: |
| 191 | if isinstance(module, str) and (not test_name or test_name == module): |
| 192 | suite.addTests(doctest.DocTestSuite(module)) |
| 193 | |
Simon Glass | 1d0f30e | 2022-01-22 05:07:28 -0700 | [diff] [blame] | 194 | for module in class_and_module_list: |
| 195 | if isinstance(module, str): |
| 196 | continue |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 197 | # Test the test module about our arguments, if it is interested |
| 198 | if hasattr(module, 'setup_test_args'): |
| 199 | setup_test_args = getattr(module, 'setup_test_args') |
| 200 | setup_test_args(preserve_indir=test_preserve_dirs, |
| 201 | preserve_outdirs=test_preserve_dirs and test_name is not None, |
| 202 | toolpath=toolpath, verbosity=verbosity) |
| 203 | if test_name: |
Alper Nebi Yasak | ce12c47 | 2022-04-02 20:06:05 +0300 | [diff] [blame] | 204 | # Since Python v3.5 If an ImportError or AttributeError occurs |
| 205 | # while traversing a name then a synthetic test that raises that |
| 206 | # error when run will be returned. Check that the requested test |
| 207 | # exists, otherwise these errors are included in the results. |
| 208 | if test_name in loader.getTestCaseNames(module): |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 209 | suite.addTests(loader.loadTestsFromName(test_name, module)) |
Simon Glass | ce0dc2e | 2020-04-17 18:09:01 -0600 | [diff] [blame] | 210 | else: |
| 211 | suite.addTests(loader.loadTestsFromTestCase(module)) |
Alper Nebi Yasak | d8318fe | 2022-04-02 20:06:06 +0300 | [diff] [blame] | 212 | |
| 213 | print(f" Running {toolname} tests ".center(70, "=")) |
| 214 | result = runner.run(suite) |
| 215 | print() |
| 216 | |
| 217 | return result |