blob: dd671965263ffaa5a800eaf71c772c79c33d9748 [file] [log] [blame]
Simon Glass132be852018-07-06 10:27:23 -06001# SPDX-License-Identifier: GPL-2.0+
2#
3# Copyright (c) 2016 Google, Inc
4#
5
Simon Glass3609d5e2018-07-06 10:27:34 -06006from contextlib import contextmanager
Simon Glassc27d22d2022-01-22 05:07:28 -07007import doctest
Simon Glass132be852018-07-06 10:27:23 -06008import glob
Simon Glass73306922020-04-17 18:09:01 -06009import multiprocessing
Simon Glass132be852018-07-06 10:27:23 -060010import os
11import sys
Simon Glass73306922020-04-17 18:09:01 -060012import unittest
Simon Glass132be852018-07-06 10:27:23 -060013
Simon Glass131444f2023-02-23 18:18:04 -070014from u_boot_pylib import command
Simon Glass132be852018-07-06 10:27:23 -060015
Simon Glass945328b2020-04-17 18:08:55 -060016from io import StringIO
Simon Glass3609d5e2018-07-06 10:27:34 -060017
Simon Glass73306922020-04-17 18:09:01 -060018use_concurrent = True
19try:
Simon Glassf715ab92023-02-23 18:18:03 -070020 from concurrencytest import ConcurrentTestSuite
21 from concurrencytest import fork_for_tests
Simon Glass73306922020-04-17 18:09:01 -060022except:
23 use_concurrent = False
24
Simon Glass3609d5e2018-07-06 10:27:34 -060025
Simon Glass0ce8fed2024-09-30 12:51:36 -060026def run_test_coverage(prog, filter_fname, exclude_list, build_dir,
27 required=None, extra_args=None, single_thread='-P1',
28 args=None):
Simon Glass132be852018-07-06 10:27:23 -060029 """Run tests and check that we get 100% coverage
30
31 Args:
32 prog: Program to run (with be passed a '-t' argument to run tests
33 filter_fname: Normally all *.py files in the program's directory will
34 be included. If this is not None, then it is used to filter the
35 list so that only filenames that don't contain filter_fname are
36 included.
37 exclude_list: List of file patterns to exclude from the coverage
38 calculation
39 build_dir: Build directory, used to locate libfdt.py
40 required: List of modules which must be in the coverage report
Simon Glass5d5930d2020-07-09 18:39:29 -060041 extra_args (str): Extra arguments to pass to the tool before the -t/test
42 arg
Simon Glassc8b99b12023-07-19 17:49:31 -060043 single_thread (str): Argument string to make the tests run
44 single-threaded. This is necessary to get proper coverage results.
45 The default is '-P0'
Simon Glass0ce8fed2024-09-30 12:51:36 -060046 args (list of str): List of tests to run, or None to run all
Simon Glass132be852018-07-06 10:27:23 -060047
48 Raises:
49 ValueError if the code coverage is not 100%
50 """
51 # This uses the build output from sandbox_spl to get _libfdt.so
52 path = os.path.dirname(prog)
53 if filter_fname:
54 glob_list = glob.glob(os.path.join(path, '*.py'))
55 glob_list = [fname for fname in glob_list if filter_fname in fname]
56 else:
57 glob_list = []
58 glob_list += exclude_list
Simon Glass102b21c2019-05-17 22:00:54 -060059 glob_list += ['*libfdt.py', '*site-packages*', '*dist-packages*']
Simon Glass6eb63c72020-07-09 18:39:34 -060060 glob_list += ['*concurrencytest*']
Simon Glass109e84e2020-07-05 21:41:55 -060061 test_cmd = 'test' if 'binman' in prog or 'patman' in prog else '-t'
Simon Glassf156e3b2020-04-17 18:09:00 -060062 prefix = ''
63 if build_dir:
64 prefix = 'PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools ' % build_dir
Simon Glassbd75bea2024-06-23 11:56:21 -060065
66 # Detect a Python virtualenv and use 'coverage' instead
67 covtool = ('python3-coverage' if sys.prefix == sys.base_prefix else
68 'coverage')
69
70 cmd = ('%s%s run '
Simon Glass0ce8fed2024-09-30 12:51:36 -060071 '--omit "%s" %s %s %s %s %s' % (prefix, covtool, ','.join(glob_list),
72 prog, extra_args or '', test_cmd,
73 single_thread or '-P1',
74 ' '.join(args) if args else ''))
Simon Glass132be852018-07-06 10:27:23 -060075 os.system(cmd)
Simon Glassbd75bea2024-06-23 11:56:21 -060076 stdout = command.output(covtool, 'report')
Simon Glass132be852018-07-06 10:27:23 -060077 lines = stdout.splitlines()
78 if required:
79 # Convert '/path/to/name.py' just the module name 'name'
80 test_set = set([os.path.splitext(os.path.basename(line.split()[0]))[0]
81 for line in lines if '/etype/' in line])
82 missing_list = required
Simon Glass0baeab72019-07-08 14:25:32 -060083 missing_list.discard('__init__')
Simon Glass132be852018-07-06 10:27:23 -060084 missing_list.difference_update(test_set)
85 if missing_list:
Simon Glass23b8a192019-05-14 15:53:36 -060086 print('Missing tests for %s' % (', '.join(missing_list)))
87 print(stdout)
Simon Glass132be852018-07-06 10:27:23 -060088 ok = False
89
90 coverage = lines[-1].split(' ')[-1]
91 ok = True
Simon Glass23b8a192019-05-14 15:53:36 -060092 print(coverage)
Simon Glass132be852018-07-06 10:27:23 -060093 if coverage != '100%':
Simon Glass23b8a192019-05-14 15:53:36 -060094 print(stdout)
Simon Glass58816412022-08-13 11:40:41 -060095 print("To get a report in 'htmlcov/index.html', type: python3-coverage html")
Simon Glass23b8a192019-05-14 15:53:36 -060096 print('Coverage error: %s, but should be 100%%' % coverage)
Simon Glass132be852018-07-06 10:27:23 -060097 ok = False
98 if not ok:
99 raise ValueError('Test coverage failure')
Simon Glass3609d5e2018-07-06 10:27:34 -0600100
101
102# Use this to suppress stdout/stderr output:
103# with capture_sys_output() as (stdout, stderr)
104# ...do something...
105@contextmanager
106def capture_sys_output():
107 capture_out, capture_err = StringIO(), StringIO()
108 old_out, old_err = sys.stdout, sys.stderr
109 try:
110 sys.stdout, sys.stderr = capture_out, capture_err
111 yield capture_out, capture_err
112 finally:
113 sys.stdout, sys.stderr = old_out, old_err
Simon Glass73306922020-04-17 18:09:01 -0600114
115
Alper Nebi Yasakfedac7b2022-04-02 20:06:07 +0300116class FullTextTestResult(unittest.TextTestResult):
117 """A test result class that can print extended text results to a stream
118
119 This is meant to be used by a TestRunner as a result class. Like
120 TextTestResult, this prints out the names of tests as they are run,
121 errors as they occur, and a summary of the results at the end of the
122 test run. Beyond those, this prints information about skipped tests,
123 expected failures and unexpected successes.
124
125 Args:
126 stream: A file-like object to write results to
127 descriptions (bool): True to print descriptions with test names
128 verbosity (int): Detail of printed output per test as they run
129 Test stdout and stderr always get printed when buffering
130 them is disabled by the test runner. In addition to that,
131 0: Print nothing
132 1: Print a dot per test
133 2: Print test names
134 """
135 def __init__(self, stream, descriptions, verbosity):
136 self.verbosity = verbosity
137 super().__init__(stream, descriptions, verbosity)
138
139 def printErrors(self):
140 "Called by TestRunner after test run to summarize the tests"
141 # The parent class doesn't keep unexpected successes in the same
142 # format as the rest. Adapt it to what printErrorList expects.
143 unexpected_successes = [
144 (test, 'Test was expected to fail, but succeeded.\n')
145 for test in self.unexpectedSuccesses
146 ]
147
148 super().printErrors() # FAIL and ERROR
149 self.printErrorList('SKIP', self.skipped)
150 self.printErrorList('XFAIL', self.expectedFailures)
151 self.printErrorList('XPASS', unexpected_successes)
152
153 def addSkip(self, test, reason):
154 """Called when a test is skipped."""
155 # Add empty line to keep spacing consistent with other results
156 if not reason.endswith('\n'):
157 reason += '\n'
158 super().addSkip(test, reason)
159
160
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300161def run_test_suites(toolname, debug, verbosity, test_preserve_dirs, processes,
Simon Glass1b53d902022-01-29 14:14:14 -0700162 test_name, toolpath, class_and_module_list):
Simon Glass73306922020-04-17 18:09:01 -0600163 """Run a series of test suites and collect the results
164
165 Args:
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300166 toolname: Name of the tool that ran the tests
Simon Glass73306922020-04-17 18:09:01 -0600167 debug: True to enable debugging, which shows a full stack trace on error
168 verbosity: Verbosity level to use (0-4)
169 test_preserve_dirs: True to preserve the input directory used by tests
170 so that it can be examined afterwards (only useful for debugging
171 tests). If a single test is selected (in args[0]) it also preserves
172 the output directory for this test. Both directories are displayed
173 on the command line.
174 processes: Number of processes to use to run tests (None=same as #CPUs)
175 test_name: Name of test to run, or None for all
176 toolpath: List of paths to use for tools
Simon Glassc27d22d2022-01-22 05:07:28 -0700177 class_and_module_list: List of test classes (type class) and module
178 names (type str) to run
Simon Glass73306922020-04-17 18:09:01 -0600179 """
Simon Glass73306922020-04-17 18:09:01 -0600180 sys.argv = [sys.argv[0]]
181 if debug:
182 sys.argv.append('-D')
183 if verbosity:
184 sys.argv.append('-v%d' % verbosity)
185 if toolpath:
186 for path in toolpath:
187 sys.argv += ['--toolpath', path]
188
189 suite = unittest.TestSuite()
190 loader = unittest.TestLoader()
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300191 runner = unittest.TextTestRunner(
192 stream=sys.stdout,
193 verbosity=(1 if verbosity is None else verbosity),
Alper Nebi Yasakfedac7b2022-04-02 20:06:07 +0300194 resultclass=FullTextTestResult,
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300195 )
196
197 if use_concurrent and processes != 1:
198 suite = ConcurrentTestSuite(suite,
Simon Glass1ca554e2023-02-23 18:18:02 -0700199 fork_for_tests(processes or multiprocessing.cpu_count()))
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300200
201 for module in class_and_module_list:
202 if isinstance(module, str) and (not test_name or test_name == module):
203 suite.addTests(doctest.DocTestSuite(module))
204
Simon Glassc27d22d2022-01-22 05:07:28 -0700205 for module in class_and_module_list:
206 if isinstance(module, str):
207 continue
Simon Glass73306922020-04-17 18:09:01 -0600208 # Test the test module about our arguments, if it is interested
209 if hasattr(module, 'setup_test_args'):
210 setup_test_args = getattr(module, 'setup_test_args')
211 setup_test_args(preserve_indir=test_preserve_dirs,
212 preserve_outdirs=test_preserve_dirs and test_name is not None,
213 toolpath=toolpath, verbosity=verbosity)
214 if test_name:
Alper Nebi Yasak71e9a4c2022-04-02 20:06:05 +0300215 # Since Python v3.5 If an ImportError or AttributeError occurs
216 # while traversing a name then a synthetic test that raises that
217 # error when run will be returned. Check that the requested test
218 # exists, otherwise these errors are included in the results.
219 if test_name in loader.getTestCaseNames(module):
Simon Glass73306922020-04-17 18:09:01 -0600220 suite.addTests(loader.loadTestsFromName(test_name, module))
Simon Glass73306922020-04-17 18:09:01 -0600221 else:
222 suite.addTests(loader.loadTestsFromTestCase(module))
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300223
224 print(f" Running {toolname} tests ".center(70, "="))
225 result = runner.run(suite)
226 print()
227
228 return result